<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Request;

/**2021年9月15日18:24:50    云仓2  线上api/controller/order
 * author 刘黎坡
 * 订单及购物车
 */
class Order extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 商品加入购物车
     *
     */
    public function add_buy_car()
    {
        $request = [
            'userhome_id' => $this->request->param('userhome_id'),//用户id
            'supplier_id' => $this->request->param("supplier_id"),//供应商id
            'goods_id' => $this->request->param('goods_id'),//商品id
            'goods_spec_one_id' => $this->request->param('goods_spec_one_id'),//一级属性id
            'goods_spec_two_id' => $this->request->param('goods_spec_two_id'),//二级属性id
            'name' => $this->request->param('name'),//商品名称
            'goods_spec_one_name' => $this->request->param('goods_spec_one_name'),//一级属性名称
            'goods_spec_two_name' => $this->request->param('goods_spec_two_name'),//二级属性名称
            'price' => $this->request->param('price'),//商品价格
            'image' => $this->request->param('image') ? replace_http($this->request->param('image')) : '',//商品图片路径
            'num' => $this->request->param('num') ?: 1,//数量
        ];
        if ($request['num'] <= 0) {
            $request['num'] = 1;
        }
        $token = $this->request->param("token") ?: 0;//
        $jm_str = $this->request->param("jm_str") ?: 0;//
        $res = yanzheng($request['userhome_id'], $token, $jm_str);
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }

        // $id = $this->request->param('id')?:'';
        /* 验证不能为空的字段*/
        $EmptyData = array('userhome_id', 'supplier_id', 'goods_id', 'goods_spec_one_id', 'name', 'goods_spec_one_name', 'price');
        foreach ($EmptyData as $oeVo) {
            $retInfo = EmptyValidate($oeVo, $request);
            if ($retInfo) {
                $this->error($retInfo, '', 201);
            }
        }
        $where = [];
        $where['userhome_id'] = $request['userhome_id'];
        $where['goods_id'] = $request['goods_id'];
        $where['goods_spec_one_id'] = $request['goods_spec_one_id'];
        $where['goods_spec_two_id'] = $request['goods_spec_two_id'];

        //先查询购物车内是否有该商品
        $res = DB::name('buy_car')->where($where)->find();
        unset($where['userhome_id']);
        $stock_num = DB::name('goods_stock')->where($where)->value('num');
        $vip_price = DB::name('goods_stock')->where($where)->value('vip_price');
        $request['vip_price'] = $vip_price;
        if ($res) {
            //查询库存数
            //判断是否超过库存数
            if ($res['num'] + $request['num'] > $stock_num) {
                $this->error('商品加购数量已超过库存', '', 201);
            } else {
                //修改购物车数量
                //购物车内当前商品直接加数量
                DB::name('buy_car')->where('id', $res['id'])->setInc('num', $request['num']);
                $this->success('ok', '', 200);
            }
        } else {//就加入购物车
            //判断是否超过库存数
            if ($request['num'] > $stock_num) {
                $this->error('商品加购数量已超过库存', '', 201);
            }
            DB::name('buy_car')->insertGetId($request);
            $this->success('社科赛斯', '', 200);
        }
    }

    //购物车数量
    public function buy_car_num()
    {
        $request = Request::instance();
        $userhome_id = $request->param("userhome_id") ?: 0;//用户id
        $token = $this->request->param("token") ?: 0;//
        $jm_str = $this->request->param("jm_str") ?: 0;//
        $res = yanzheng($userhome_id, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        //$arr = DB::name('buy_car')->where('userhome_id', $userhome_id)->count();

        $arr = DB::name('buy_car t1')
            ->join('goods t2', 't1.goods_id = t2.id')
            ->where('t1.userhome_id', $userhome_id)->count();
        // dump($arr);die;
        $this->success('OK', $arr, 200);
    }

    //购物车商品生成订单前-请求运费模板
    public function car_yunfei_moban()
    {
        $request = Request::instance();
        $expressfee_ids = $request->param("expressfee_ids");//模板id,多个用,拼接
        // $expressfee_ids = DB::name('goods')->where('id','in',$goods_id)->group('expressfee_id')->column('expressfee_id');
        $arr = DB::name('expressfee')->where('id', 'in', $expressfee_ids)->select();
        // dump($arr);
        $this->success('OK', $arr, 200);
    }

    //查询商品是否有库存
    public function get_goods_stock()
    {
        $request = Request::instance();
        $where = [];
        $goods_id = $request->param("goods_id");
        $goods_integral_id = $request->param("goods_integral_id");
        if ($goods_id) {
            $where['goods_id'] = $request->param("goods_id");
        }
        if ($goods_integral_id) {
            $where['goods_integral_id'] = $request->param("goods_integral_id");
        }
        $where['goods_spec_one_id'] = $request->param("goods_spec_one_id");
        $where['goods_spec_two_id'] = $request->param("goods_spec_two_id") ?: 0;
        $num = $request->param("num") ?: 1;//最终的数量

        $stock_num = DB::name('goods_stock')->where($where)->value('num');//商品实际库存数
        if ($num > $stock_num) {
            $this->error('商品加购数量已超过库存', $stock_num, 201);
        }
        $this->success('OK', '', 200);
    }

    //-购物车数量增加
    public function add_car_num()
    {
        $request = Request::instance();
        $id = $request->param("id");//购物车id
        $num = $request->param("num") ?: 1;//最终的数量
        if ($num <= 0) {
            DB::name('buy_car')->where('id', $id)->delete();
        } else {
            //查询该商品实际库存数
            $car_arr = DB::name('buy_car')->where('id', $id)->find();
            $where = [];
            // $where['userhome_id'] = $request['userhome_id'];
            $where['goods_id'] = $car_arr['goods_id'];
            $where['goods_spec_one_id'] = $car_arr['goods_spec_one_id'];
            $where['goods_spec_two_id'] = $car_arr['goods_spec_two_id'];
            $stock_num = DB::name('goods_stock')->where($where)->value('num');//商品实际库存数
            if ($num > $stock_num) {
                $this->error('商品加购数量已超过库存', $stock_num, 201);
            } else {
                DB::name('buy_car')->where('id', $id)->update(['num' => $num]);
            }

        }
        $this->success('OK', '', 200);

    }

    //删除购物车
    public function delete_car()
    {
        $request = Request::instance();
        $id = $request->param("id");//购物车id
        DB::name('buy_car')->where('id', 'in', $id)->delete();
        $this->success('OK', '', 200);

    }

    //购物车商品移动至收藏夹
    public function move_favorites()
    {
        $request = Request::instance();
        $id = $request->param("id");//购物车id
        $idList = explode(',', $id);
        $car_arr = DB::name('buy_car')->whereIn('id', $idList)->select();
        //先添加到收藏夹
        foreach ($car_arr as $value) {
            $u_yincang = ['userhome_id' => $value['userhome_id'], 'goods_id' => $value['goods_id']];
            $yin = DB::name('usercollection')->where($u_yincang)->find();
            if (!$yin) {
                DB::name('usercollection')->insertGetId($u_yincang);
            }
        }
        DB::name('buy_car')->whereIn('id', $idList)->delete();
        $this->success('OK', '', 200);
    }

    //购物车列表
    public function buy_car_list()
    {
        $request = Request::instance();
        $userhome_id = $request->param("userhome_id") ?: 0;//用户id
        $res = yanzheng($userhome_id, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $arr = DB::name('buy_car t1')
            ->join('goods t2', 't1.goods_id = t2.id')
            ->where('t1.userhome_id', $userhome_id)->order('t1.id', 'desc')->field('t1.*')->select();
        if ($arr) {
            foreach ($arr as $key => $value) {
                $gys = DB::name('goods')->where('id', $value['goods_id'])->field('expressfee_id,zhongliang,supplier_id')->find();
                $arr[$key]['expressfee_id'] = $gys['expressfee_id'];
                $arr[$key]['zhongliang'] = $gys['zhongliang'];
                $arr[$key]['supplier_id'] = $gys['supplier_id'];

                $arr[$key]['image'] = path($value['image']);
                //查询是否缺货
                $where = [];
                $where['goods_id'] = $value['goods_id'];
                $where['goods_spec_one_id'] = $value['goods_spec_one_id'];
                $where['goods_spec_two_id'] = $value['goods_spec_two_id'];
                $stock_num = DB::name('goods_stock')->where($where)->value('num');
                $use_integral = DB::name('goods_stock')->where($where)->value('use_integral');
                if ($value['num'] > $stock_num) {
                    $is_qh = 0;//0= 缺货
                } else {
                    $is_qh = 1;//1=正常
                }
                $arr[$key]['is_qh'] = $is_qh;
                $arr[$key]['use_integral'] = $use_integral;
                $arr[$key]['expressfee_info'] = DB::name('expressfee')->where('id', $arr[$key]['expressfee_id'])->find();

            }
        }
        $this->success('OK', $arr, 200);
    }


    //添加收藏
    public function add_shoucang()
    {
        $request = Request::instance();
        $userhome_id = $request->param("userhome_id") ?: 0;//用户id
        $res = yanzheng($userhome_id, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $goods_id_list = $request->param("goods_id") ?: 0;//商品id
        $goods_id_list = explode(',', $goods_id_list);
        foreach ($goods_id_list as $value) {
            $u_yincang = ['userhome_id' => $userhome_id, 'goods_id' => $value];
            $yin = DB::name('usercollection')->where($u_yincang)->find();
            if (!$yin) {
                DB::name('usercollection')->insertGetId($u_yincang);
            }
        }
        $this->success('OK', '', 200);
    }

    //取消收藏
    public function qx_shoucang()
    {
        $request = Request::instance();
        $userhome_id = $request->param("userhome_id") ?: 0;//用户id
        $res = yanzheng($userhome_id, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $goods_id = $request->param("goods_id") ?: 0;//商品id

        $u_yincang = ['userhome_id' => $userhome_id, 'goods_id' => $goods_id];
        DB::name('usercollection')->where($u_yincang)->delete();
        $this->success('OK', '', 200);
    }

    //取消隐藏
    public function qx_yincang()
    {
        $request = Request::instance();
        $userhome_id = $request->param("userhome_id") ?: 0;//用户id
        $res = yanzheng($userhome_id, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $goods_id = $request->param("goods_id") ?: 0;//商品id

        $u_yincang = ['userhome_id' => $userhome_id];
        DB::name('useryincang')->where($u_yincang)->where('goods_id', 'in', $goods_id)->delete();
        $this->success('OK', '', 200);
    }

    //检查当前地址是否支持发货
    public function jc_address()
    {
        $request = Request::instance();
        $cityid = $request->param("city_id") ?: 0;//市id
        $is_integral = $request->param("is_integral") ?: 0;//市id
        $goods_ids = $request->param("goods_ids") ?: 0;//商品id 多个用,拼接
        if ($is_integral) {
            $goods_arr = DB::name('goods_integral')->where('id', 'in', $goods_ids)->field('id,supplier_id,expressfee_id')->select();
        } else {
            $goods_arr = DB::name('goods')->where('id', 'in', $goods_ids)->field('id,supplier_id,expressfee_id')->select();
        }
        // $arr = explode(',',$goods_ids);
        $res = 0;
        foreach ($goods_arr as $key => $value) {
            $res = DB::name('expressfeecity')->where('supplier_id', $value['supplier_id'])->where('expressfeeid', $value['expressfee_id'])->where('cityid', $cityid)->find();
            if (!$res) {
                //$this->error('该地区不支持发货', '', 201);
            }
        }
        $this->success('OK', '', 200);

    }

    //获取商品税率
    public function get_shuilv($goods_id)
    {
        return DB::name('goods')->where('id', $goods_id)->value('shuilv');
    }

//    //立即购买生成订单
//    public function create_order()
//    {
//        $request = Request::instance();
//        $inviteCode = $request->param("inviteCode");
//        $inviteCodeUser = DB::name('userhome')->where('inviteCode', $inviteCode)->find();
//        $inviteUserId = null;
//        if ($inviteCodeUser) {
//            $inviteUserId = $inviteCodeUser['id'];
//        }
//        $order = [
//            'is_activity' => $request->param("is_activity") ?: 0,//:0=非活动订单,1=活动订单
//            'userhome_id' => $request->param("userhome_id"),//用户id
//            'supplier_id' => $request->param("supplier_id"),//供应商id
//            'price' => $request->param("price"),//商品总金额
//            'freight' => $request->param("freight") ?: 0,//运费
//            'dikou' => $request->param("dikou") ?: 0,//购物立减券
//            'is_yc' => $request->param("is_yc") ?: 0,
//
//            'coupon' => $request->param("coupon") ?: 0,//优惠券
//            'allprice' => $request->param("allprice"),//实付款
//            'phone' => $request->param("phone"),//用户手机号
//            'name' => $request->param("name"),//用户名称
//            'address' => $request->param("address"),//用户地址
//            'inviteUserId' => $inviteUserId,//分享人手机号
//            'createtime' => time(),//下单时间
//            //生成支付单号
//            'paycode' => date('Ymd') . '1' . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . rand(0, 9),//生成支付单号
//            //生成订单号
//            'ordernum' => date('Ymd') . '2' . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 6, 12), 1))), 0, 8) . rand(0, 9),//生成订单号
//
//        ];
//        $res = yanzheng($order['userhome_id'], $this->request->param("token"), $this->request->param("jm_str"));
//        if ($res == 0) {
//            $this->error('账号异常', '', 206);
//        }
//        if ($res == 1) {
//            $this->error('非法的请求', '', 201);
//        }
//        if ($order['allprice'] < 0) {
//            $this->error('下单失败,订单总额有误', '', 201);
//        }
//        if ($order['is_activity'] == 1) {//活动订单查询是否超时
//            $g_id = $request->param("goods_id");
//            $etime = DB::name('seckill')->where('goods_id', $g_id)->value('etime');
//            if (time() > $etime) {
//                $this->error('订单超时下单失败', '', 201);
//            }
//        }
//        $couponsuser_id = $request->param("coupon_id") ?: 0;//优惠券id
//        $is_yc = $request->param("is_yc") ?: 0;//是否隐藏该订单商品 1=隐藏,0=不隐藏
//        /* 验证不能为空的字段*/
//        $EmptyData = array('userhome_id', 'supplier_id', 'price', 'allprice', 'phone', 'name', 'address');
//        foreach ($EmptyData as $oeVo) {
//            $retInfo = EmptyValidate($oeVo, $order);
//            if ($retInfo) {
//                $this->error($retInfo, '', 201);
//            }
//        }
//        //查询用户的立减券是多少
//        $vouchers = DB::name('userhome')->where('id', $order['userhome_id'])->value('vouchers');
//        if ($order['dikou'] > $vouchers) {
//            $this->error('立减券余额不足', '', 201);
//        }
//
//        $orderdetail = [
//            'userhome_id' => $request->param("userhome_id"),//用户id
//            'goods_id' => $request->param("goods_id"),//商品id
//            'shuilv' => $this->get_shuilv($request->param("goods_id")),//商品税率
//
//            'image' => $request->param("image") ? replace_http($this->request->param('image')) : '',//商品图片地址
//            'name' => $request->param("goods_name"),//商品名称
//            'goods_spec_name' => $request->param("goods_spec_name"),//商品类别名称
//            'num' => $request->param("num"),//商品数量
//            'price' => $request->param("d_price"),//商品单价
//            'goods_spec_one_id' => $request->param("goods_spec_one_id"),//商品一级id
//            'goods_spec_two_id' => $request->param("goods_spec_two_id"),//商品二级id
//            'return_mode_id' => DB::name('goods')->where('id', $request->param("goods_id"))->value('return_mode_id'),
//            'integral' => DB::name('goods_stock')->where(['goods_spec_one_id' => $request->param("goods_spec_one_id"), 'goods_spec_two_id' => $request->param("goods_spec_two_id")])->value('use_integral'),
//            //成本单价
//            'cost_price' => $this->get_cost_price($request->param("goods_id"), $request->param("goods_spec_one_id"), $request->param("goods_spec_two_id")),
//
//        ];
//        /* 验证不能为空的字段*/
//        $EmptyData = array('goods_id', 'name', 'goods_spec_name', 'num', 'price');
//        foreach ($EmptyData as $oeVo) {
//            $retInfo = EmptyValidate($oeVo, $orderdetail);
//            if ($retInfo) {
//                $this->error($retInfo, '', 201);
//            }
//        }
//        //生成订单
//        $order['supplier_cost'] = $this->get_cost_price($orderdetail['goods_id'], $orderdetail['goods_spec_one_id'], $orderdetail['goods_spec_two_id']) * $orderdetail['num'];
//        $order_id = DB::name('order')->insertGetId($order);
//        $orderdetail['order_id'] = $order_id;
//        //订单详情
//        DB::name('orderdetail')->insertGetId($orderdetail);
//        //添加隐藏商品
//        if ($is_yc) {
//            $u_yincang = ['userhome_id' => $order['userhome_id'], 'goods_id' => $orderdetail['goods_id']];
//            $yin = DB::name('useryincang')->where($u_yincang)->find();
//            if (!$yin) {
//                DB::name('useryincang')->insertGetId($u_yincang);
//            }
//
//        }
//        //判断是否使用优惠券
//        if ($couponsuser_id != 0) {
//            //作废掉已使用的优惠券
//            DB::name('couponsuser')->where('id', $couponsuser_id)->update(['status' => 1]);//改成已使用
//        }
//        //判断是否使用立减券
//        if ($order['dikou'] > 0) {
//            // 用户表减去对应的券额,生成立减券消费记录
//            DB::name('userhome')->where('id', $order['userhome_id'])->setDec('vouchers', $order['dikou']);
//            DB::name('userhome')->where('id', $order['userhome_id'])->update(['end_xf_time' => time()]);
//            $vouchers = [
//                'userhome_id' => $order['userhome_id'],
//                'bean_num' => $order['dikou'],
//                'type' => 1,
//                'createtime' => time(),
//            ];
//            DB::name('vouchers')->insertGetId($vouchers);
//        }
//
//        //返回支付单号
//        $this->success('OK', ['code' => $order['paycode'], 'order_id' => $order_id], 200);
//
//    }

//    //购物车生成订单
//    public function car_create_order()
//    {
//        $request = Request::instance();
//        $buy_car_id = $request->param("buy_car_id") ?: 0;//多个购物车id用,拼接
//        $userhome_id = $request->param("userhome_id");//用户id
//
//        $res = yanzheng($userhome_id, $this->request->param("token"), $this->request->param("jm_str"));
//        if ($res == 0) {
//            $this->error('账号异常', '', 206);
//        }
//        if ($res == 1) {
//            $this->error('非法的请求', '', 201);
//        }
//        $supplier_id = $request->param("supplier_id");//供应商id,多个用,拼接
//        $price = $request->param("price");//供应商下的商品总金额  多个供应商下的用,拼接
//        $freight = $request->param("freight") ?: 0;//运费  多个供应商下的用,拼接 如果是0 写0,不可为空
//
//        $dikou = $request->param("dikou") ?: 0;//购物立减券            ㄱ
//        $coupon = $request->param("coupon") ?: 0;//优惠券              ㅏ   按订单总额比例分
//        $allprice = $request->param("allprice");//实付款            ㅢ
//
//        $phone = $request->param("phone");//用户电话
//        $name = $request->param("name");//用户名称
//        $address = $request->param("address");//用户地址
//        $createtime = time();//下单时间
//        $couponsuser_id = $request->param("coupon_id") ?: 0;//优惠券id
//
//        $goods_id = $request->param("goods_id");//商品id,单个供应商用,拼接   1,2-3,4多个供应商下用≁拼接
//        $goods_spec_one_id = $request->param("goods_spec_one_id");//商品id,单个供应商用,拼接   1,2-3,4多个供应商下用≁拼接
//        $goods_spec_two_id = $request->param("goods_spec_two_id");//商品id,单个供应商用,拼接   1,2-3,4多个供应商下用≁拼接
//
//
//        $image = $request->param("image") ? replace_http($this->request->param('image')) : '';//商品图片地址  1,2-3,4多个供应商下用≁拼接
//        $goods_name = $request->param("goods_name");//商品名称,多个用,拼接  1,2-3,4多个供应商下用≁拼接
//        $goods_spec_name = $request->param("goods_spec_name");//商品类别名称,多个用,拼接  1,2-3,4多个供应商下用≁拼接
//        $num = $request->param("num");//商品数量,多个用,拼接  1,2-3,4多个供应商下用≁拼接
//        $d_price = $request->param("d_price");//商品单价,多个用,拼接  1,2-3,4多个供应商下用≁拼接
//
//        $is_yc = $request->param("is_yc") ?: 0;//是否隐藏该订单商品 1=隐藏,0=不隐藏
//        //查询用户的立减券是多少
//        $vouchers = DB::name('userhome')->where('id', $userhome_id)->value('vouchers');
//        if ($dikou > $vouchers) {
//            $this->error('立减券余额不足', '', 201);
//        }
//
//        $supplier_arr = explode(',', $supplier_id);
//        $price_arr = explode(',', $price);
//        $freight_arr = explode(',', $freight);
//        //商品相关
//        $goods_id_arr = explode('≁', $goods_id);
//        $image_arr = explode('≁', $image);
//        $goods_name_arr = explode('≁', $goods_name);
//        $goods_spec_name_arr = explode('≁', $goods_spec_name);
//        $num_arr = explode('≁', $num);
//        $d_price_arr = explode('≁', $d_price);
//        $goods_spec_one_id_arr = explode('≁', $goods_spec_one_id);
//        $goods_spec_two_id_arr = explode('≁', $goods_spec_two_id);
//
//        foreach ($goods_id_arr as $key => $value) {
//            $goods_id_arr[$key] = explode(',', $goods_id_arr[$key]);
//            $image_arr[$key] = explode(',', $image_arr[$key]);
//            $goods_name_arr[$key] = explode(',', $goods_name_arr[$key]);
//            $goods_spec_name_arr[$key] = explode(',', $goods_spec_name_arr[$key]);
//            $num_arr[$key] = explode(',', $num_arr[$key]);
//            $d_price_arr[$key] = explode(',', $d_price_arr[$key]);
//            $goods_spec_one_id_arr[$key] = explode(',', $goods_spec_one_id_arr[$key]);
//            $goods_spec_two_id_arr[$key] = explode(',', $goods_spec_two_id_arr[$key]);
//
//        }
//
//        //查询占比
//        $sum_money = array_sum($price_arr);
//        $count_num = count($price_arr);
//
//        // 生成订单
//        $ljq = 0;
//        $yhq = 0;
//
//        $order_data = [];
//        //生成支付单号
//        $paycode = date('Ymd') . '1' . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . rand(0, 9);//生成支付单号
//        foreach ($supplier_arr as $key => $value) {
//            $order_data['paycode'] = $paycode;
//            $order_data['ordernum'] = date('Ymd') . '2' . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 6, 12), 1))), 0, 8) . rand(0, 9);//生成订单号;
//            $order_data['phone'] = $phone;
//            $order_data['name'] = $name;
//            $order_data['address'] = $address;
//            $order_data['createtime'] = $createtime;
//            $order_data['userhome_id'] = $userhome_id;
//            $order_data['supplier_id'] = $supplier_arr[$key];//供应商id
//            $order_data['price'] = $price_arr[$key];//商品总金额
//
//            $order_data['freight'] = $freight_arr[$key];//运费
//            $order_data['is_yc'] = $is_yc;//隐藏
//
//            // 计算单个供应商 对应的购物立减券  和  优惠券≁
//            if ($key + 1 == $count_num) {//判断是最后一个  优惠券减去前面所有的优惠券,立减券减去前面所有的立减券
//                $d_dikou = $dikou - $ljq;
//                $d_coupon = $coupon - $yhq;
//                // echo $d_dikou;
//                // echo '<br/>';
//                // echo $d_coupon;die;
//            } else {
//                $d_dikou = number_format($price_arr[$key] / $sum_money * $dikou, '2');
//                $ljq += $d_dikou;
//                $d_coupon = number_format($price_arr[$key] / $sum_money * $coupon, '2');
//                $yhq += $d_coupon;
//            }
//            $order_data['dikou'] = $d_dikou;
//            $order_data['coupon'] = $d_coupon;
//            $order_data['allprice'] = $price_arr[$key] - $d_dikou - $d_coupon + $freight_arr[$key];//实付款-购物立减券-优惠券+运费
//            // if ($order_data['allprice'] < 0) {
//            //     $this->error('下单失败,订单总额有误','',201);
//            // }
//            //生成订单
//            $order_id = DB::name('order')->insertGetId($order_data);
//            //生成订单详情
//            $order_detail = [];
//            $cost = 0;
//            foreach ($goods_id_arr[$key] as $k3 => $v3) {
//                $order_detail[$k3]['order_id'] = $order_id;
//                $order_detail[$k3]['goods_id'] = $goods_id_arr[$key][$k3];
//                $order_detail[$k3]['shuilv'] = $this->get_shuilv($goods_id_arr[$key][$k3]);//税率
//
//                $order_detail[$k3]['return_mode_id'] = DB::name('goods')->where('id', $goods_id_arr[$key][$k3])->value('return_mode_id');
//                $order_detail[$k3]['integral'] = DB::name('goods_stock')->where(['goods_spec_one_id' => $goods_spec_one_id_arr[$key][$k3], 'goods_spec_two_id' => $goods_spec_two_id_arr[$key][$k3]])->value('use_integral');
//                $order_detail[$k3]['goods_spec_one_id'] = $goods_spec_one_id_arr[$key][$k3];
//                if (isset($goods_spec_two_id_arr[$key][$k3]) && !empty($goods_spec_two_id_arr[$key][$k3])) {
//                    $order_detail[$k3]['goods_spec_two_id'] = $goods_spec_two_id_arr[$key][$k3];
//                } else {
//                    $order_detail[$k3]['goods_spec_two_id'] = 0;
//                }
//                $cost += $this->get_cost_price($order_detail[$k3]['goods_id'], $order_detail[$k3]['goods_spec_one_id'], $order_detail[$k3]['goods_spec_two_id']) * $num_arr[$key][$k3];
//                //成本单价
//                $order_detail[$k3]['cost_price'] = $this->get_cost_price($order_detail[$k3]['goods_id'], $order_detail[$k3]['goods_spec_one_id'], $order_detail[$k3]['goods_spec_two_id']);
//
//
//                $order_detail[$k3]['image'] = $image_arr[$key][$k3];
//                $order_detail[$k3]['name'] = $goods_name_arr[$key][$k3];
//                $order_detail[$k3]['goods_spec_name'] = $goods_spec_name_arr[$key][$k3];
//                $order_detail[$k3]['num'] = $num_arr[$key][$k3];
//                $order_detail[$k3]['price'] = $d_price_arr[$key][$k3];
//                $order_detail[$k3]['userhome_id'] = $userhome_id;
//                //添加隐藏商品
//                if ($is_yc) {
//                    $u_yincang = ['userhome_id' => $userhome_id, 'goods_id' => $order_detail[$k3]['goods_id']];
//                    $yin = DB::name('useryincang')->where($u_yincang)->find();
//                    if (!$yin) {
//                        DB::name('useryincang')->insertGetId($u_yincang);
//                    }
//
//                }
//
//
//            }
//            DB::name('order')->where('id', $order_id)->update(['supplier_cost' => $cost]);
//            DB::name('orderdetail')->insertAll($order_detail);
//        }
//        //判断是否使用优惠券
//        if ($couponsuser_id != 0) {
//            //作废掉已使用的优惠券
//            DB::name('couponsuser')->where('id', $couponsuser_id)->update(['status' => 1]);//改成已使用
//        }
//        //判断是否使用立减券
//        if ($dikou > 0) {
//            // 用户表减去对应的券额,生成立减券消费记录
//            DB::name('userhome')->where('id', $userhome_id)->setDec('vouchers', $dikou);
//            DB::name('userhome')->where('id', $userhome_id)->update(['end_xf_time' => time()]);
//            $vouchers = [
//                'userhome_id' => $userhome_id,
//                'bean_num' => $dikou,
//                'type' => 1,
//                'createtime' => time(),
//            ];
//            DB::name('vouchers')->insertGetId($vouchers);
//        }
//        //删除购物车
//        DB::name('buy_car')->where('id', 'in', $buy_car_id)->delete();
//        $this->success('OK', ['code' => $paycode, 'order_id' => $order_id], 200);
//    }

    //添加隐藏商品
    public function add_yincang()
    {
        $request = Request::instance();
        $order_id = $request->param("order_id") ?: 0;//订单id
        $goods_id = $request->param("goods_id") ?: 0;//商品id,多个用,拼接
        $userhome_id = $request->param("userhome_id") ?: 0;//用户id
        $goods_id_arr = explode(',', $goods_id);
        $res = yanzheng($userhome_id, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }

        $u_yincang = ['userhome_id' => $userhome_id];
        foreach ($goods_id_arr as $key => $value) {
            $u_yincang['goods_id'] = $value;

            $yin = DB::name('useryincang')->where($u_yincang)->find();
            if (!$yin) {
                DB::name('useryincang')->insertGetId($u_yincang);
            }
        }
        DB::name('order')->where('id', $order_id)->update(['is_yincang' => 1]);
        $this->success('ok', '', 200);

    }

    //省市区三级联动
    public function get_city()
    {
        //
        $str = DB::name('all_city')->value('text');
        $this->success('返回成功', json_decode($str, true));
        die;


        //
        $region = DB::name('district');
        $res = $region->where('level', 1)->field('district_id as id,district as text')->select();
        foreach ($res as $key => $value) {
            $res[$key]['data'] = $region->where('pid', $value['id'])->field('district_id as id,district as text')->select();
            foreach ($res[$key]['data'] as $kk => $vv) {
                $res[$key]['data'][$kk]['data'] = $region->where('pid', $vv['id'])->field('district_id as id,district as text')->select();
            }
        }
        $text = json_encode($res, JSON_UNESCAPED_UNICODE);
        DB::name('all_city')->where('id', 1)->update(['text' => $text]);
        echo 200;
        die;
        dump(json_encode($res, JSON_UNESCAPED_UNICODE));
        die;
        $this->success('成功', $res, 200);

    }

    //用户地址列表
    public function user_address_list()
    {
        $request = Request::instance();
        $userhome_id = $request->param("userhome_id") ?: 0;//用户id

        $token = $request->param("token") ?: 0;//
        $jm_str = $request->param("jm_str") ?: 0;//
        $res = yanzheng($userhome_id, $token, $jm_str);
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $arr = DB::name('useraddress')->where('userhome_id', $userhome_id)->order('is_default desc')->select();
        if ($arr) {
            foreach ($arr as $key => $value) {
                $arr[$key]['areyouok'] = $value['pro_name'] . $value['city_name'] . $value['area_name'] . $value['address'];
            }
        }
        $this->success('OK', $arr, 200);

    }

    //删除用户地址
    public function del_address()
    {
        $request = Request::instance();
        $id = $request->param("id") ?: 0;//地址id
        $userhome_id = $request->param("userhome_id") ?: 0;//用户id
        $res = yanzheng($userhome_id, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        DB::name('useraddress')->where('id', $id)->where('userhome_id', $userhome_id)->delete();
        $this->success('OK', '', 200);
    }

    //新增编辑地址
    public function add_address()
    {
        $request = [
            'userhome_id' => $this->request->param('userhome_id'),//用户id
            'name' => $this->request->param('name'),//联系人
            'phone' => $this->request->param('phone'),//电话
            'pro_id' => $this->request->param('pro_id'),//省id
            'city_id' => $this->request->param('city_id'),//市id
            'area_id' => $this->request->param('area_id'),//区id
            'pro_name' => $this->request->param('pro_name'),//省名称
            'city_name' => $this->request->param('city_name'),//市名称
            'area_name' => $this->request->param('area_name'),//区名称
            'address' => $this->request->param('address'),//详细地址
            'is_default' => $this->request->param('is_default') ?: 0
        ];
        $res = yanzheng($request['userhome_id'], $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $id = $this->request->param('id') ?: '';
        $is_default = $request['is_default'];
        /* 验证不能为空的字段*/
        $EmptyData = array('userhome_id', 'phone', 'pro_id', 'area_id', 'name', 'city_id', 'pro_name', 'area_name', 'city_name', 'address');
        foreach ($EmptyData as $oeVo) {
            if ($oeVo == "address") {
                if (!isset($request['address']) || empty($request['address']))
                    $this->error("详细地址不可为空");
            }
            $retInfo = EmptyValidate($oeVo, $request);
            if ($retInfo) {
                $this->error($retInfo, '', 201);
            }
        }
        if ($id) {
            DB::name('useraddress')->where('id', $id)->update($request);
        } else {
            $id = DB::name('useraddress')->insertGetId($request);
        }
        if ($is_default == 1) {
            DB::name('useraddress')->where('id', '<>', $id)->where('userhome_id', $request['userhome_id'])->update(['is_default' => 0]);
        }
        $this->success('OK', '', 200);
    }

    //订单列表
    public function order_list()
    {
        $request = Request::instance();
        $userhome_id = $request->param("userhome_id") ?: 0;//用户id
        $res = yanzheng($userhome_id, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $status = $request->param("status") ?: 1;//1=待支付,2=已支付(待发货),3=已发货(待收货,4=待评价,11=售后(is_shouhou=1),99=全部订单
        $page = $request->param("page") ? $request->param("page") : 1;    //页数
        $page_count = $request->param("page_count") ? $request->param("page_count") : 10;    //条数
        $where = [];
        if ($status == 11) {
            $where['is_shouhou'] = 1;
            $order = DB::name('order a')
                ->join('orderdetail b', 'a.id=b.order_id')
                ->join('yc_order_return c', 'b.id = c.orderdetail_id and c.is_new = 1', "LEFT")
                ->where('a.userhome_id', $userhome_id)
                ->where('a.is_integral', 0)
                ->whereRaw('b.is_shouhou != 0')
                ->order('a.id desc')
                ->field('a.id,a.ordernum,a.allprice,a.createtime,a.status,a.fahuotime,a.is_yincang,b.id orderdetail_id,shouhuotime,a.is_integral,a.use_integral,c.shouhou_status,c.return_type,c.schedule')
                ->paginate($page_count);
            $totalNum = $order->total();
            $order = $order->items();
        } elseif ($status == 99) {
            $where['status'] = ['<>', 9];
            $order = DB::name('order')
                ->where('userhome_id', $userhome_id)
                ->where($where)
                ->where('is_integral', 0)
                ->whereRaw('status != 6')
                ->page($page, $page_count)
                ->order('id desc')
                ->field('id,ordernum,allprice,createtime,status,fahuotime,is_yincang,is_kaipiao,shouhuotime,is_integral,use_integral')
                ->paginate($page_count);
            $totalNum = $order->total();
            $order = $order->items();
        } else {
            $where['status'] = $status;
            if ($status == 1) {
                $where['createtime'] = ['>', time() - 1800];
            }
            $order = DB::name('order')
                ->where('userhome_id', $userhome_id)
                ->whereRaw("(select count(*) from yc_orderdetail where yc_orderdetail.order_id = yc_order.id and yc_orderdetail.is_shouhou not in(1,2)) != 0")
                ->where('is_integral', 0)
                ->where($where)
                ->page($page, $page_count)
                ->order('id desc')
                ->field('id,ordernum,allprice,createtime,status,fahuotime,is_yincang,is_kaipiao,shouhuotime,is_integral,use_integral')
                ->paginate($page_count);
            $totalNum = $order->total();
            $order = $order->items();
        }

        if ($order) {
            $orderdetail_where = [];
            $orderdetail = DB::name('orderdetail');
            foreach ($order as $key => $value) {
                if (!empty($value['shouhuotime'])) {
                    if ($value['shouhuotime'] + 7 * 86400 < time()) {
                        $order[$key]['is_7day'] = 1;
                    } else {

                        $order[$key]['is_7day'] = 0;
                    }
                } else {
                    $order[$key]['is_7day'] = 0;
                }
                $order[$key]['goods_id'] = '';
                if ($status == 11) {
                    $orderdetail_where['id'] = $value['orderdetail_id'];
                }
                $detail = $orderdetail
                    ->where($orderdetail_where)
                    ->where('order_id', $value['id'])
                    ->field('id,goods_id,image,name,goods_spec_name,tkprice, tkyy,remark,shhimages,thnum,price,num,is_shouhou,leave,evaluate,images,goods_spec_two_id,goods_spec_one_id,integral,vip_price')
                    ->order('id desc')->select();

                // dump($detail);die;
                foreach ($detail as $k => $v) {
                    $shh_img_arr = [];
                    if ($v['shhimages']) {
                        // code...
                        $shh_images = explode(',', $v['shhimages']);
                        foreach ($shh_images as $k_img => $v_img) {
                            $shh_img_arr[$k_img] = path($v_img);
                        }
                    }
                    $detail[$k]['shh_img_arr'] = $shh_img_arr;
                    $detail[$k]['goods_spec_two_name'] = '';
                    $detail[$k]['goods_spec_one_name'] = $v['goods_spec_name'];
                    if ($value['is_integral']) {
                        $expressfee_id = DB::name('goods_integral')->where('id', $v['goods_id'])->value('expressfee_id');
                        $detail[$k]['zhongliang'] = DB::name('goods_integral')->where('id', $v['goods_id'])->value('zhongliang');
                    } else {
                        $expressfee_id = DB::name('goods')->where('id', $v['goods_id'])->value('expressfee_id');
                        $detail[$k]['zhongliang'] = DB::name('goods')->where('id', $v['goods_id'])->value('zhongliang');
                    }
                    $detail[$k]['expressfee_info'] = DB::name('expressfee')->where('id', $expressfee_id)->find();
                    $detail[$k]['image'] = path($v['image']);
                    $order[$key]['goods_id'] .= $v['goods_id'] . ',';
                    if ($status == 11) {
                        //$detail[$k]['price'] = $v['tkprice'];
                        // code...
                        $order[$key]['is_shouhou'] = $v['is_shouhou'];
                        $order[$key]['id'] = $v['id'];
                        $order[$key]['allprice'] = $v['tkprice'];

                        $order[$key]['thnum'] = $v['thnum'];
                    }


                }
                $order[$key]['goods_id'] = trim($order[$key]['goods_id'], ',');
                $order[$key]['detail'] = $detail;
                if ($value['status'] == 1) {
                    $order[$key]['djs'] = $value['createtime'] + 1800 - time();
                } elseif ($value['status'] == 3) {
                    $order[$key]['djs'] = $value['fahuotime'] + 86400 * 7 - time();
                } else {
                    $order[$key]['djs'] = 0;
                }

            }
        }
        $arr = $order;
        foreach ($arr as $key => $value) {
            if (empty($value['detail'])) {
                // dump($order[$key]);
                unset($arr[$key]);
            }
            // code...
        }
        // dump(array_merge($arr));
        if ($status == 11) {
            $order = array_merge($arr);
        }
        // die;
        $this->success($totalNum, $order, 200);

    }

    //订单详情页
    public function order_detail()
    {
        $request = Request::instance();
        $order_id = $request->param("order_id") ?: 0;//订单id
        if (!$order_id) {
            $this->error('缺少订单id', '', 201);
        }
        $order = DB::name('order')->where('id', $order_id)->find();
        $detail = DB::name('orderdetail')->where('order_id', $order_id)
            ->field('id,image,name,goods_spec_name,price,num,leave,evaluate,images,pjtime,is_pingjia,goods_spec_two_id,goods_spec_one_id,goods_id,tkprice, thnum,tkyy,remark,shhimages,is_shouhou,integral,vip_price')->select();
        foreach ($detail as $k => $v) {
            $shh_images = explode(',', $v['shhimages']);
            $shh_img_arr = [];
            foreach ($shh_images as $k_img => $v_img) {
                $shh_img_arr[$k_img] = path($v_img);
            }
            $detail[$k]['shh_img_arr'] = $shh_img_arr;
            $detail[$k]['image'] = path($v['image']);
            $detail[$k]['goods_spec_two_name'] = '';
            $detail[$k]['goods_spec_one_name'] = $v['goods_spec_name'];
            if ($order['is_integral']) {
                $expressfee_id = DB::name('goods_integral')->where('id', $v['goods_id'])->value('expressfee_id');
                $detail[$k]['zhongliang'] = DB::name('goods_integral')->where('id', $v['goods_id'])->value('zhongliang');
            } else {
                $expressfee_id = DB::name('goods')->where('id', $v['goods_id'])->value('expressfee_id');
                $detail[$k]['zhongliang'] = DB::name('goods')->where('id', $v['goods_id'])->value('zhongliang');
            }
            $detail[$k]['expressfee_info'] = DB::name('expressfee')->where('id', $expressfee_id)->find();
            if ($v['pjtime']) {
                $detail[$k]['pjtime'] = date('Y-m-d H:i:s', $detail[$k]['pjtime']);
            }
            if ($v['images']) {
                $images = explode(',', $v['images']);
                $imgs = [];
                foreach ($images as $k1 => $v1) {
                    $imgs[$k1] = path($v1);
                }
                $detail[$k]['pjimages'] = $imgs;
            } else {
                $detail[$k]['pjimages'] = [];
            }
            unset($detail[$k]['images']);

        }

        if ($order['status'] == 1) {
            $order['djs'] = $order['createtime'] + 1800 - time();
        } elseif ($order['status'] == 3) {
            $order['djs'] = $order['fahuotime'] + 86400 * 7 - time();
        } else {
            $order['djs'] = 0;
        }

        $order['createtime'] = date('Y-m-d H:i:s', $order['createtime']);
        $order['cancelTime'] = date('Y-m-d H:i:s', $order['cancelTime']);
        if ($order['paytime']) {
            $order['paytime'] = date('Y-m-d H:i:s', $order['paytime']);
        }
        if ($order['fahuotime']) {
            $order['fahuotime'] = date('Y-m-d H:i:s', $order['fahuotime']);
        }
        // dump($order);die;
        if ($order['shouhuotime']) {
            $shouhuotime = date('Y-m-d H:i:s', $order['shouhuotime']);
            if ($order['shouhuotime'] + 7 * 86400 < time()) {
                $order['is_7day'] = 1;
            } else {

                $order['is_7day'] = 0;
            }
            $order['shouhuotime'] = $shouhuotime;
        } else {

            $order['is_7day'] = 0;
        }
        $order['detail'] = $detail;
        unset($order['paycode']);
        $this->success('社科赛斯', $order, 200);
    }

    //取消订单
    public function qx_order()
    {
        $request = Request::instance();
        $arr['id'] = $request->param("order_id") ?: 0;//订单id
        $arr['userhome_id'] = $request->param("userhome_id") ?: 0;//用户id
        $res = yanzheng($arr['userhome_id'], $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        DB::name('order')->where($arr)->where('status', 1)->update(['status' => 0, 'cancelTime' => time()]);
        //查看是否有使用立减券
//        $dikou = DB::name('order')->where($arr)->value('dikou');
//        if ($dikou > 0) {//对应的立减券需要返还给用户
//            DB::name('userhome')->where('id', $arr['userhome_id'])->setInc('vouchers', $dikou);
//            $vouchers = [
//                'userhome_id' => $arr['userhome_id'],
//                'bean_num' => $dikou,
//                'type' => 7,
//                'createtime' => time(),
//            ];
//            DB::name('userhome')->where('id', $arr['userhome_id'])->update(['end_rz_time' => time()]);
//            DB::name('vouchers')->insertGetId($vouchers);
//        }
        $this->success('社科赛斯', '', 200);

    }

    //查看物流
    public function get_wuliu()
    {
        $request = Request::instance();
        $id = $request->param("id");//订单id
        $res = DB::name('order')->where('id', $id)->field('wuliu_num,wuliu_code,wuliu_name,break')->find();
        if (empty($res['wuliu_num'])) {
            $this->error('未获取到物流信息', '', 201);
        }
        // $com = 'yunda';//快递公司编码
        // $num = '43110074702781';//单号
        $com = $res['wuliu_code'];
        $num = $res['wuliu_num'];
        $break = $res['break'];
        $wuliu = kuaidi($com, $num);
        // dump($wuliu);die;
        $wuliu = objectToArray($wuliu);
        if ($wuliu['message'] == 'ok') {
            $arr['wuliu_name'] = $res['wuliu_name'];
            $arr['wuliu_name'] = $res['wuliu_name'];
            $arr['wuliu_num'] = $num;
            $arr['break'] = $break;
            $arr['data'] = $wuliu['data'];

            $this->success('成功', $arr, 200);
        } else {
            $arr['wuliu_name'] = $res['wuliu_name'];
            $arr['wuliu_num'] = $num;
            $arr['break'] = $break;
            $arr['data'] = [];
            $this->success('成功', $arr, 200);
            // $this->error('未获取到物流信息',$arr,201);
        }
    }

    //删除订单
    public function del_order()
    {
        $request = Request::instance();
        $arr['id'] = $request->param("order_id") ?: 0;//订单id
        $arr['userhome_id'] = $request->param("userhome_id") ?: 0;//用户id
        // $arr['userhome_id'] = $request->param("userhome_id")?:0;//用户id
        $res = yanzheng($arr['userhome_id'], $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $status = DB::name('order')->where($arr)->value('status');
        if ($status == 0 || $status == 1) {
            DB::name('order')->where($arr)->delete();
            DB::name('orderdetail')->where('order_id', $arr['id'])->delete();

        } else {

            DB::name('order')->where($arr)->update(['status' => 9]);
        }
        $this->success('社科赛斯', '', 200);
    }

    //确认收货
    public function enter_shouhuo()
    {
        $request = Request::instance();
        $arr['id'] = $request->param("order_id") ?: 0;//订单id
        $arr['userhome_id'] = $request->param("userhome_id") ?: 0;//用户id
        $res = yanzheng($arr['userhome_id'], $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }

        try {
            Db::startTrans();
            $order = Db::name("order")->where($arr)->find();
            if (!$order) {
                $this->error('没有订单,无法收货', '', 2013);
                return;
            }
            if ($order['status'] != 3) {
                $this->error('没有订单,无法收货', '', 2013);
                return;
            }
            $levelList = Db::name("level")->select();
            $this->integralEnter($order, $levelList);
            DB::name('order')->where($arr)->update(['status' => 5, 'shouhuotime' => time()]);
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('社科赛斯', '', 200);
    }

    //积分到账处理/$all意思为是否自动操作 1是
    public function integralEnter($order, $levelList)
    {
        if (!$order['is_integral'] && ($order['activityStatus'] == 0 || $order['activityStatus'] == 10)) {
            $userIncomeScoreLogList = DB::name('user_income_score_log t1')
                ->join('orderdetail t2', 't1.order_detail_id = t2.id')
                ->whereIn('t2.is_shouhou', [0, 3])
                ->where(['t1.order_id' => $order['id'], 't1.status' => "WAIT"])
                ->field('t1.*')
                ->select();
            foreach ($userIncomeScoreLogList as $value) {
                $levelIntegral = null;
                $levelShopIntegral = null;
                $lastLevelId = -1;
                DB::name('userhome')->where(['id' => $value['userId']])->setInc("use_integral", $value['score']);
                DB::name('userhome')->where(['id' => $value['userId']])->setInc("add_integral", $value['score']);
                if ($value['source'] == "SHOP") {
                    DB::name('userhome')->where(['id' => $value['userId']])->setInc("shop_integral", $value['score']);
                }
                $user = DB::name('userhome')->where(['id' => $value['userId']])->lock(true)->find();
                if ($user) {
                    $this->upLevel($levelList, $user);
                }
                Db::name("user_income_score_log")->where(['incomeScoreLogId' => $value['incomeScoreLogId']])->update([
                    'consumeScore' => $user['use_integral'],
                    'grandScore' => $user['add_integral'],
                    'status' => "ENTER"
                ]);
            }
            $userTeamPriceLog = DB::name('user_team_price_log t1')
                ->join('orderdetail t2', 't1.order_detail_id = t2.id')
                ->whereIn('t2.is_shouhou', [0, 3])
                ->where(['t1.order_id' => $order['id'], 't1.status' => "WAIT"])
                ->field('t1.*')
                ->select();
            unset($value);
            foreach ($userTeamPriceLog as $value) {
                DB::name('userhome')->where(['id' => $value['userId']])->setInc("consumePrice", $value['price']);
                DB::name('userhome')->where(['id' => $value['userId']])->setInc("grandPrice", $value['price']);
                DB::name('userhome')->where(['id' => $value['userId']])->setDec("lockPrice", $value['price']);
                $user = DB::name('userhome')->where(['id' => $value['userId']])->lock(true)->find();
                Db::name("user_team_price_log")->where(['userTeamPriceLogId' => $value['userTeamPriceLogId']])->update([
                    'consumePrice' => $user['consumePrice'],
                    'grandPrice' => $user['grandPrice'],
                    'withdrawPrice' => $user['withdrawPrice'],
                    'status' => "ENTER"
                ]);
            }
        }
    }

    public function upLevel($levelList, $user)
    {
        $levelIntegral = 0;
        $lastLevelId = 0;
        $levelShopIntegral = 0;
        foreach ($levelList as $key => $level) {
            if ($level['levelId'] == ($user['levelId'] + 1)) {
                $levelIntegral = $level['integral'];
                $levelShopIntegral = $level['shop_integral'];
                $lastLevelId = $level['levelId'];
                break;
            }
        }
        if ($levelIntegral && ($lastLevelId > 0) && isset($levelShopIntegral)) {
            if (($user['add_integral'] >= $levelIntegral) && ($user['shop_integral'] >= $levelShopIntegral)) {
                DB::name('userhome')->where(['id' => $user['id']])->update(['levelId' => $lastLevelId]);
            }
        }
    }

    //提醒商家发货
    public function tx_fahuo()
    {
        $request = Request::instance();
        $arr['id'] = $request->param("order_id") ?: 0;//订单id

        DB::name('order')->where($arr)->setInc('tx_fahuo');
        $this->success('已经提醒商家', '', 200);
    }

    //添加发票OR修改发票
    public function add_fapiao()
    {
        $request = Request::instance();
        $fapiao = [
            'userhome_id' => $request->param("userhome_id"),//用户id
            // 'type' => $request->param("type")?:1,//发票类型:1=普通发票 2=专用发票
            'head_type' => $request->param("head_type") ?: 1,//抬头类型:1=个人,2=企业
            'name' => $request->param("name"),//发票抬头
            'code' => $request->param("code"),//税号
            'address' => $request->param("address"),//地址
            'phone' => $request->param("phone"),//电话
            'bank' => $request->param("bank"),//开户行
            'number' => $request->param("number"),//开户账号
            'email' => $request->param("email"),//邮箱
            'remark' => $request->param("remark"),//备注
        ];
        $arr['userhome_id'] = $request->param("userhome_id") ?: 0;//用户id
        $res = yanzheng($arr['userhome_id'], $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $id = $request->param("id") ?: 0;//发票id
        /* 验证不能为空的字段*/
        $EmptyData = array('userhome_id', 'name', 'code');
        foreach ($EmptyData as $oeVo) {
            $retInfo = EmptyValidate($oeVo, $fapiao);
            if ($retInfo) {
                $this->error($retInfo, '', 201);
            }
        }
        if ($id) {
            DB::name('invoice')->where('id', $id)->update($fapiao);
        } else {
            DB::name('invoice')->insert($fapiao);
        }
        $this->success('社科赛斯', '', 200);
    }

    //发票列表
    public function fapiao_list()
    {
        $request = Request::instance();
        $arr['userhome_id'] = $request->param("userhome_id") ?: 0;//用户id
        $res = yanzheng($arr['userhome_id'], $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $fapiao = DB::name('invoice')->where($arr)->select();
        $this->success('社科赛斯', $fapiao, 200);
    }

    //删除发票
    public function del_fapiao()
    {
        $request = Request::instance();
        $arr['id'] = $request->param("id") ?: 0;//发票id
        $arr['userhome_id'] = $request->param("userhome_id") ?: 0;//用户id
        $res = yanzheng($arr['userhome_id'], $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }

        DB::name('invoice')->where($arr)->delete();
        $this->success('社科赛斯', '', 200);
    }

    //申请开票
    public function sq_kaipiao()
    {
        $request = Request::instance();
        $order_id = $request->param("order_id") ?: 0;//订单id
        $userhome_id = $request->param("userhome_id") ?: 0;//用户id
        $res = yanzheng($userhome_id, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $invoice_id = $request->param("invoice_id") ?: 0;//发票id
        $fapiao = DB::name('invoice')->where('id', $invoice_id)->where('userhome_id', $userhome_id)->find();
        $fapiao['order_id'] = $order_id;
        unset($fapiao['id']);
        $invoice_id = DB::name('invoice_order')->insertGetId($fapiao);
        DB::name('order')->where('id', $order_id)->update(['invoice_id' => $invoice_id, 'is_kaipiao' => 1]);
        $this->success('社科赛斯', '', 200);
    }

    //评价订单
    public function pj_order()
    {
        $request = Request::instance();
        $userhome_id = $request->param("userhome_id") ?: 0;//用户id
        $res = yanzheng($userhome_id, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $pjtime = time();
        $is_pingjia = 1;
        //评价订单的json串
        // id  订单详情id
        // leave  星级  1-5
        // evaluate  评价内容
        // images  评价图片路径,多个用,拼接
        // $json = [["id"=>1,"leave"=>5,"evaluate"=>"评价内容","images"=>"\/a.jpg,b.jpg"]];
        $json = $request->param("json/a");
        $arr = $json;
        // $arr = json_decode($json,true);
        // dump($json);die;
        foreach ($arr as $key => $value) {
            $arr[$key]['pjtime'] = time();
            $arr[$key]['is_pingjia'] = 1;
            DB::name('orderdetail')->where('id', $value['id'])->update($arr[$key]);
            $order_id = DB::name('orderdetail')->where('id', $value['id'])->value('order_id');
        }
        //订单状态改成已完成状态
        DB::name('order')->where('id', $order_id)->update(['status' => 5]);
        // ***暂定***   如果多张子订单只评价一个 把所有的子订单都改为已评价状态  如果不合适在修改
        DB::name('orderdetail')->where('order_id', $order_id)->update(['is_pingjia' => 1]);

        $this->success('社科赛斯', '', 200);
    }


    //申请售后
    public function sq_shouhou()
    {
        $request = Request::instance();
        $id = $request->param("id");//订单详情id
        $userhome_id = $request->param("userhome_id") ?: 0;//用户id
        $res = yanzheng($userhome_id, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $return_type = [
            "MONEY" => "仅退款",
            "HAM" => "退货退款",
            "EXCHANE" => "换货"
        ];
        $arr['return_type'] = $request->param("return_type");//售后类型 MONEY仅退款 HAM退货退款 EXCHANE换货
        $arr['break'] = $request->param("break");//退款原因
        $image = $request->param("image");//售后图片路径 多张图片用,拼接
        $image_list = [];
        if (isset($image) && !empty($image)) {
            $image = explode(';', $image);
            foreach ($image as $key => $value) {
                $image_list[] = path($value);
            }
        }
        if (isset($image_list[0])) {
            $arr['image'] = implode(';', $image_list);
        } else {
            $arr['image'] = null;
        }
        if (!$arr['return_type'] || !$arr['break']) {
            $this->error('参数不全,请检查', '', 30018);
        }
        $orderDetatil = DB::name('orderdetail')->where('id', $id)->where('userhome_id', $userhome_id)->find();
        if (!$orderDetatil) {
            $this->error('未查询到该订单', '', 30019);
        }
        $order = DB::name('order')->where('id', $orderDetatil['order_id'])->find();
        if (!$order) {
            $this->error('未查询到该订单', '', 30019);
        }
        if ($order['is_integral']) {
            $this->error('积分订单不允许售后', '', 30020);
        }
        $time = time();
        $payTime = $order['paytime'] + 1296000;
        if ($time > $payTime) {
            $this->error('已超出15天限制，无法进行售后', '', 30021);
        }
        if ($orderDetatil['is_shouhou'] == 1 || $orderDetatil['is_shouhou'] == 2) {
            $this->error('售后进行中，无法再次进行售后', '', 30022);
        }
        if (($order['status'] != 2) && ($order['status'] != 3) && ($order['status'] != 6)) {
            $this->error('订单已完成，无法再次进行售后', '', 30023);
        }
        try {
            Db::startTrans();
            if ($order['allprice'] == 0) {
                $this->error('免费订单不允许售后', '', 30024);
            }
            if ($order['oldAllPirce'] == 0) {
                DB::name('order')->where('id', $orderDetatil['order_id'])->update(['oldAllPirce' => $order['allprice']]);
            }
            $realityFreight = 0;
            if ($order['versions'] == 0) {
                if ($order['oldAllPirce'] == 0) {
                    $discountsPrice = $order['price'] - $order['allprice'];
                } else {
                    $discountsPrice = $order['price'] - $order['oldAllPirce'];
                }
                $goodTotalNum = DB::name('orderdetail')->where('order_id', $order['id'])->where('userhome_id', $userhome_id)->sum('num');
                $oneGoodDiscountsPrice = $discountsPrice / $goodTotalNum;
                $tkprice = ($orderDetatil['price'] * $orderDetatil['num']) - ($oneGoodDiscountsPrice * $orderDetatil['num']);
            } else if ($order['versions'] == 1) {
                $isGo = 1;
                if ($order['status'] != 6) {
                    if ($order['status'] == 2) {
                        $isGo = 0;
                    }
                } else {
                    if ($order['oldStatus'] == 2) {
                        $isGo = 0;
                    }
                }
                $tkprice = $orderDetatil['realityPrice'];
                if (!$isGo) {
                    $tkprice = $tkprice + $orderDetatil['realityFreight'];
                    $realityFreight = $orderDetatil['realityFreight'];
                }
            }
            if ($order['status'] != 6) {
                $num = DB::name('orderdetail')->where('order_id', $orderDetatil['order_id'])->where('id != ' . $id)->whereNotIn('is_shouhou', [1, 2])->count();
                if (!$num) {
                    DB::name('order')->where('id', $orderDetatil['order_id'])->update(['is_shouhou' => 1, 'oldStatus' => $order['status'], 'status' => 6]);
                }
            }
            DB::name('order')->where('id', $orderDetatil['order_id'])->update(['is_shouhou' => 1]);
            DB::name('orderdetail')->where('id', $id)->update(['is_shouhou' => 1, 'tkprice' => $tkprice, 'shouhoutime' => time()]);
            DB::name('order_return')->where('orderdetail_id', $id)->update(['is_new' => 0]);
            $order_return = [];
            $order_return['order_id'] = $orderDetatil['order_id'];
            $order_return['orderdetail_id'] = $orderDetatil['id'];
            $order_return['return_type'] = $arr['return_type'];
            $order_return['image'] = $arr['image'];
            $order_return['break'] = $arr['break'];
            $order_return['realityFreight'] = $realityFreight;
            $order_return['createTime'] = date("Y-m-d H:i:s");
            $order_return_id = DB::name('order_return')->insertGetId($order_return);
            $yc_order_negotiation_history = [];
            $yc_order_negotiation_history['order_id'] = $orderDetatil['order_id'];
            $yc_order_negotiation_history['orderdetail_id'] = $orderDetatil['id'];
            $yc_order_negotiation_history['order_return_id'] = $order_return_id;
            $yc_order_negotiation_history['is_user'] = 1;
            $yc_order_negotiation_history['content'] = "用户发起了" . $return_type[$arr['return_type']] . "申请";
            $yc_order_negotiation_history['image'] = $arr['image'];
            $yc_order_negotiation_history['break'] = $arr['break'];
            $yc_order_negotiation_history['createTime'] = date("Y-m-d H:i:s");
            DB::name('order_negotiation_history')->insertGetId($yc_order_negotiation_history);
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('社科赛斯', $orderDetatil['order_id'], 200);
    }

    //售后说明
    public function sm_shouhou()
    {
        $request = Request::instance();
        $id = $request->param("id");//订单详情id
        $userhome_id = $request->param("userhome_id") ?: 0;//用户id
        $res = yanzheng($userhome_id, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $orderDetatil = DB::name('orderdetail')->where('id', $id)->where('userhome_id', $userhome_id)->find();
        if (!$orderDetatil) {
            $this->error('未查询到该订单', '', 30019);
        }
        $orderDetatil['image'] = path($orderDetatil['image']);
        $orderDetatil['return_type'] = null;
        $orderDetatil['return_break'] = null;
        $orderDetatil['return_image'] = null;
        $orderDetatil['service_image'] = null;
        $orderDetatil['service_break'] = null;
        $orderDetatil['shouhou_status'] = null;
        $orderDetatil['shouhou_wuliu_name'] = null;
        $orderDetatil['shouhou_wuliu_no'] = null;
        $orderDetatil['createTime'] = null;
        $orderDetatil['schedule'] = null;
        $order_return = DB::name('order_return')->where('orderdetail_id', $id)->where('is_new', 1)->find();
        if ($order_return) {
            $image = explode(';', $order_return['image']);
            $return_image_list = [];
            foreach ($image as $key => $value) {
                $return_image_list[] = path($value);
            }
            $image = explode(';', $order_return['service_image']);
            $service_image_list = [];
            foreach ($image as $key => $value) {
                $service_image_list[] = path($value);
            }
            $orderDetatil['return_type'] = $order_return['return_type'];
            $orderDetatil['return_break'] = $order_return['break'];
            $orderDetatil['return_image'] = $return_image_list;
            $orderDetatil['service_image'] = $service_image_list;
            $orderDetatil['service_break'] = $order_return['service_break'];
            $orderDetatil['shouhou_status'] = $order_return['shouhou_status'];
            $orderDetatil['schedule'] = $order_return['schedule'];
            $orderDetatil['shouhou_wuliu_name'] = $order_return['shouhou_wuliu_name'];
            $orderDetatil['shouhou_wuliu_no'] = $order_return['shouhou_wuliu_no'];
            $orderDetatil['createTime'] = $order_return['createTime'];
        }
        $this->success('社科赛斯', $orderDetatil, 200);
    }

    //协商历史
    public function xsls_shouhou()
    {
        $request = Request::instance();
        $id = $request->param("id");//订单详情id
        $userhome_id = $request->param("userhome_id") ?: 0;//用户id
        $res = yanzheng($userhome_id, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $orderDetatil = DB::name('orderdetail')->where('id', $id)->where('userhome_id', $userhome_id)->find();
        if (!$orderDetatil) {
            $this->error('未查询到该订单', '', 30019);
        }
        $negotiation = DB::name('order_negotiation_history')->where('orderdetail_id', $id)->order("createTime", "desc")->select();
        foreach ($negotiation as $key => $value) {
            if (!$value['is_user']) {
                $negotiation[$key]['content'] = $value['content'] . " 回复内容:" . $value['break'];
            }
        }
        DB::name('order_negotiation_history')->where('orderdetail_id', $id)->where('is_user', 0)->update(['is_read' => 1]);
        $this->success('社科赛斯', $negotiation, 200);
    }

    //寄回提交
    public function jh_shouhou()
    {
        $request = Request::instance();
        $id = $request->param("id");//订单详情id
        $shouhou_wuliu_name = $request->param("shouhou_wuliu_name");//订单详情id
        $shouhou_wuliu_no = $request->param("shouhou_wuliu_no");//订单详情id
        $userhome_id = $request->param("userhome_id") ?: 0;//用户id
        if (!$shouhou_wuliu_no) {
            $this->error('请输入订单号', '', 30021);
        }
        $res = yanzheng($userhome_id, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $orderDetatil = DB::name('orderdetail')->where('id', $id)->where('userhome_id', $userhome_id)->find();
        if (!$orderDetatil) {
            $this->error('未查询到该订单', '', 30019);
        }
        DB::name('order_return')->where('orderdetail_id', $id)->where('is_new', 1)->update(['shouhou_wuliu_no' => $shouhou_wuliu_no, 'shouhou_wuliu_name' => $shouhou_wuliu_name, 'schedule' => 'RETERUN']);
        $order_return = DB::name('order_return')->where('orderdetail_id', $id)->where('is_new', 1)->find();
        $yc_order_negotiation_history = [];
        $yc_order_negotiation_history['order_id'] = $orderDetatil['order_id'];
        $yc_order_negotiation_history['orderdetail_id'] = $orderDetatil['id'];
        $yc_order_negotiation_history['order_return_id'] = $order_return['id'];
        $yc_order_negotiation_history['is_user'] = 1;
        $yc_order_negotiation_history['content'] = "用户填写回寄单号:" . $shouhou_wuliu_no;
        $yc_order_negotiation_history['shouhou_wuliu_no'] = $shouhou_wuliu_no;
        $yc_order_negotiation_history['shouhou_wuliu_name'] = $shouhou_wuliu_name;
        $yc_order_negotiation_history['createTime'] = date("Y-m-d H:i:s");
        DB::name('order_negotiation_history')->insertGetId($yc_order_negotiation_history);
        $this->success('社科赛斯', '成功', 200);
    }

    public function up_order_address()
    {
        $request = Request::instance();
        $userhome_id = $request->param("userhome_id") ?: 0;//用户id
        $res = yanzheng($userhome_id, $this->request->param("token"), $this->request->param("jm_str"));
        if ($res == 0) {
            $this->error('账号异常', '', 206);
        }
        if ($res == 1) {
            $this->error('非法的请求', '', 201);
        }
        $id = $request->param("id");//订单id
        $phone = $request->param("phone");//用户手机号
        $name = $request->param("name");//用户名称
        $address = $request->param("address");//用户地址
        $freight = $request->param("freight");//运费
        if (!$id || !$phone || !$name || !$address || !isset($freight)) {
            $this->error('参数不完整,请校验传入参数', '', 30059);
        }
        $order = DB::name('order')->where('id', $id)->where('userhome_id', $userhome_id)->find();
        if (!$order) {
            $this->error('未查询到订单', '', 30060);
        }
        if ($order['update_address_num'] >= 2) {
            $this->error('该订单修改地址次数已到达上限,请勿修改', '', 30061);
        }
        if ($order['status'] != 1) {
            $this->error('该订单已发货,请勿修改', '', 30062);
        }
        if ($freight != $order['freight']) {
            $differenceFreight = $freight - $order['freight'];
            $allprice = $order['allprice'] + $differenceFreight;
        } else {
            $allprice = $order['allprice'];
        }
        $update = [
            'phone' => $phone,
            'name' => $name,
            'address' => $address,
            'freight' => $freight,
            'allprice' => $allprice,
            'update_address_num' => $order['update_address_num'] + 1
        ];
        DB::name('order')->where('id', $id)->where('userhome_id', $userhome_id)->update($update);
        $this->success('社科赛斯', '成功', 200);
    }

    //取消售后
//    public function qx_shouhou()
//    {
//        $request = Request::instance();
//        $id = $request->param("id");//订单详情id
//        $arr['shouhoutime'] = time();//售后时间
//        $arr['is_shouhou'] = 0;
//        // $arr['tkyy'] = '';
//        // $arr['thnum'] = '';
//        // $arr['tkprice'] = '';
//        // $arr['shhimages'] = '';
//        // $arr['remark'] = '';
//        DB::name('orderdetail')->where('id', $id)->update($arr);
//        $this->success('社科赛斯', '', 200);
//    }

    //订单自动取消
    public function auto_qx_order()
    {
        Db::name("userhome")->where('isVip', 1)->where('vipTime', '<=', date("Y-m-d H:i:s"))->update(['isVip' => 0]);
        $system = Db::name("system")->where('systemId', 1)->find();
        try {
            if ($system['isGet'] == 0) {
                Db::name("system")->where('systemId', 1)->update(['isGet' => 1]);
                $cronLog = [];
                $cronLog['url'] = "auto_qx_order";
                $cronLog['createTime'] = date("Y-m-d H:i:s");
                DB::name('cron_log')->insert($cronLog);
                set_time_limit(0);
                // 任务2
                //待支付订单超过30分钟自动取消
                $info = DB::name('order')->where('createtime', '<', time() - 900)->where('status', 1)->select();
                if ($info) {
                    $order = DB::name('order');
                    foreach ($info as $key => $value) {
                        $order->where('id', $value['id'])->update(['status' => 0, 'cancelTime' => time()]);
                        //查看是否有使用立减券
                        if ($value['dikou'] > 0) {
                            DB::name('userhome')->where('id', $value['userhome_id'])->setInc('vouchers', $value['dikou']);
                            $vouchers = [
                                'userhome_id' => $value['userhome_id'],
                                'bean_num' => $value['dikou'],
                                'type' => 7,
                                'createtime' => time(),
                            ];
                            DB::name('userhome')->where('id', $value['userhome_id'])->update(['end_rz_time' => time()]);
                            DB::name('vouchers')->insertGetId($vouchers);
                        }
                    }
                }
                // 任务3
                //自动确认收货 每分钟执行1次
                $this->auto_shouhuo();
                $this->auto_7day_shouhuo();
                $this->auto_gys_ddtb();
                $this->ceshis();
                //$this->auto_s_or_u_fanquan();
                Db::name("system")->where('systemId', 1)->update(['isGet' => 0]);
            }
        } catch (ValidateException $e) {
            Db::name("system")->where('systemId', 1)->update(['isGet' => 0]);
        } catch (PDOException $e) {
            Db::name("system")->where('systemId', 1)->update(['isGet' => 0]);
        } catch (Exception $e) {
            Db::name("system")->where('systemId', 1)->update(['isGet' => 0]);
        }
    }

    public function test()
    {
        $good = Db::name("goods t1")
            ->join("district t2", 't1.province_id = t2.district_id', "LEFT")
            ->join("district t3", 't1.city_id = t3.district_id', "LEFT")
            ->field("t1.id,t1.name,t1.image,t1.price,t1.old_price,t1.sale_num,t1.integral,t2.district as province,t3.district as city")
            ->select();
        foreach ($good as $value) {
            Db::name("goods")->where('id', $value['id'])->update(['province' => $value['province'], 'city' => $value['city']]);
        }
        return var_dump($good);
//        $this->auto_shouhuo();
//        $this->auto_7day_shouhuo();
//        $this->auto_gys_ddtb();
//        $this->ceshis();
    }

    public function auto_qx_order_query()
    {
        $system = Db::name("system")->where('systemId', 1)->find();
        try {
            if ($system['isQuery'] == 0) {
                Db::name("system")->where('systemId', 1)->update(['isQuery' => 1]);
                $cronLog = [];
                $cronLog['url'] = "auto_qx_order_query";
                $cronLog['createTime'] = date("Y-m-d H:i:s");
                DB::name('cron_log')->insert($cronLog);
                $this->queryOrderWx();
                Db::name("system")->where('systemId', 1)->update(['isQuery' => 0]);
            }
        } catch (ValidateException $e) {
            Db::name("system")->where('systemId', 1)->update(['isQuery' => 0]);
        } catch (PDOException $e) {
            Db::name("system")->where('systemId', 1)->update(['isQuery' => 0]);
        } catch (Exception $e) {
            Db::name("system")->where('systemId', 1)->update(['isQuery' => 0]);
        }
    }

    //测试时间
    public function ceshis()
    {
        DB::name('ems')->insert(['event' => date("Y-m-d H:i:s")]);

    }

    //自动确认收货
    public function auto_shouhuo()
    {
        $cronLog = [];
        $cronLog['url'] = "auto_shouhuo";
        $cronLog['createTime'] = date("Y-m-d H:i:s");
        DB::name('cron_log')->insert($cronLog);
        set_time_limit(0);
        //查询已发货超过7天的订单置为已完成状态
        $info = DB::name('order')->where('fahuotime', '<=', time() - 7 * 24 * 3600)->where('status', 3)->select();
        $levelList = Db::name("level")->select();
        // dump($info);
        if ($info) {
            $order = DB::name('order');
            foreach ($info as $key => $value) {
                $this->integralEnter($value, $levelList);
                $order->where('id', $value['id'])->update(['status' => 5, 'shouhuotime' => time()]);//发货超过7天置为已完成状态
            }
        }
    }

    public function supplier_statistics()
    {
        $cronLog = [];
        $cronLog['url'] = "supplier_statistics";
        $cronLog['createTime'] = date("Y-m-d H:i:s");
        DB::name('cron_log')->insert($cronLog);
        // 任务1
        // 自动添加供应商订单数量   -   每天23点58分执行一次
        $this->auto_supplier_order_num();
        //任务4 每日0点后处理供应商昨日订单统计
        $this->aotu_supplier_order_tj(0);
    }

    public function up_luck()
    {
        $cronLog = [];
        $cronLog['url'] = "up_luck";
        $cronLog['createTime'] = date("Y-m-d H:i:s");
        DB::name('cron_log')->insert($cronLog);
        DB::name('userhome')->whereRaw('id != 0')->update(['is_luck' => 0]);
        //任务4 每日0点后处理供应商昨日订单统计
        $this->aotu_supplier_order_tj(1);
    }

    //自动添加供应商订单数量   -   每天23点58分执行一次
    public function auto_supplier_order_num()
    {
        set_time_limit(0);
        $dates = date("Y-m-d");
        $supplier_order_tj = DB::name('supplier_order_tj')->where('date', $dates)->find();
        if (!$supplier_order_tj) {//如果没有添加 开始添加 ,否则不重复执行
            $cronLog = [];
            $cronLog['url'] = "auto_supplier_order_num";
            $cronLog['createTime'] = date("Y-m-d H:i:s");
            DB::name('cron_log')->insert($cronLog);
            // code...
            $supplier_arr = DB::name('supplier')->where('is_del', 0)->field('id')->select();
            $arr = [];
            foreach ($supplier_arr as $key => $value) {
                $arr[$key]['supplier_id'] = $value['id'];
                $arr[$key]['date'] = $dates;
                $arr[$key]['time'] = time();
            }
            DB::name('supplier_order_tj')->insertAll($arr);
        }
    }

    //自动统计供应商   昨日   订单数量和金额
    public function aotu_supplier_order_tj($day)
    {
        set_time_limit(0);
        $cronLog = [];
        $cronLog['url'] = "aotu_supplier_order_tj";
        $cronLog['createTime'] = date("Y-m-d H:i:s");
        DB::name('cron_log')->insert($cronLog);
        //查询昨天的全部供应商id
        $suppliser = DB::name('supplier_order_tj')->where('date', date('Y-m-d', strtotime("-$day day")))->field('supplier_id,id')->select();
        $order = DB::name('order');
        $orderdetail = DB::name('orderdetail');
        $where = [];
        $where['status'] = ['not in', '0,1,6'];
        foreach ($suppliser as $key => $value) {
            $startTime = strtotime(date('Y-m-d', strtotime("-$day day")) . " 00:00:00");
            $endTime = strtotime(date('Y-m-d', strtotime("-$day day")) . " 23:59:59");
            $da = [];
            $da['order_num'] = $order->where($where)->where('supplier_id', $value['supplier_id'])->where('is_integral', 0)->where('createtime', '>=', $startTime)->where('createtime', '<=', $endTime)->count();
            $da['order_money'] = $order->where($where)->where('supplier_id', $value['supplier_id'])->where('is_integral', 0)->where('createtime', '>=', $startTime)->where('createtime', '<=', $endTime)->sum('allprice');
            // code...
            $jiesuan_money = 0;
            $order_ids = $order->where($where)->where('supplier_id', $value['supplier_id'])->where('is_integral', 0)->where('createtime', '>=', $startTime)->where('createtime', '<=', $endTime)->column('id');
            $goods_ids = $orderdetail->where('order_id', 'in', $order_ids)->field('goods_id,num,goods_spec_one_id,goods_spec_two_id')->select();
            foreach ($goods_ids as $k => $v) {
                // $price += $goods->where('id',$v['goods_id'])->value('cost_price') * $v['num'];
                $jiesuan_money += $this->get_cost_price($v['goods_id'], $v['goods_spec_one_id'], $v['goods_spec_two_id']) * $v['num'];
            }
            $da['integral_order_num'] = $order->where($where)->where('supplier_id', $value['supplier_id'])->where('is_integral', 1)->where('createtime', '>=', $startTime)->where('createtime', '<=', $endTime)->count();
            $da['integral_order_money'] = $order->where($where)->where('supplier_id', $value['supplier_id'])->where('is_integral', 1)->where('createtime', '>=', $startTime)->where('createtime', '<=', $endTime)->sum('allprice');
            $integral_jiesuan_money = 0;
            $order_ids = $order->where($where)->where('supplier_id', $value['supplier_id'])->where('is_integral', 1)->where('createtime', '>=', $startTime)->where('createtime', '<=', $endTime)->column('id');
            $goods_ids = $orderdetail->where('order_id', 'in', $order_ids)->field('goods_id,num,goods_spec_one_id,goods_spec_two_id')->select();
            foreach ($goods_ids as $k => $v) {
                // $price += $goods->where('id',$v['goods_id'])->value('cost_price') * $v['num'];
                $integral_jiesuan_money += $this->get_cost_price($v['goods_id'], $v['goods_spec_one_id'], $v['goods_spec_two_id'], 1) * $v['num'];
            }
            $da['integral_jiesuan_money'] = $integral_jiesuan_money;
            $da['jiesuan_money'] = $jiesuan_money;
            $da['uptime'] = date('Y-m-d H:i:s');
            // dump($da);die;
            DB::name('supplier_order_tj')->where('id', $value['id'])->update($da);
        }
    }

    //计算商品成本
    public function get_cost_price($goods_id = 0, $goods_spec_one_id = 0, $goods_spec_two_id = 0, $is_integral = 0)
    {
        if ($is_integral == 1) {
            $cost_price = DB::name('goods_stock')->where('goods_integral_id', $goods_id)
                ->where('goods_spec_one_id', $goods_spec_one_id)->where('goods_spec_two_id', $goods_spec_two_id)->value('cost_price');
        } else {
            $cost_price = DB::name('goods_stock')->where('goods_id', $goods_id)
                ->where('goods_spec_one_id', $goods_spec_one_id)->where('goods_spec_two_id', $goods_spec_two_id)->value('cost_price');
        }
        if ($cost_price == 0) {
            $cost_price = DB::name('goods')->where('id', $goods_id)->value('cost_price');
        }
        return $cost_price;
    }

    //支付之前判断库存
    public function pd_kucun($paycode)
    {
        $type = substr($paycode, 8, 1);
        //判断是支付单号,还是订单号
        $where = [];
        if ($type == 1) {//支付单号=1,合并支付  
            // 查询该订单下所有商品库存信息
            $where['paycode'] = $paycode;
        } elseif ($type == 2) { //2= 拆单支付
            $where['ordernum'] = $paycode;
        }
        $order_ids = DB::name('order')->where($where)->column('id');
        $arr = DB::name('orderdetail')->where('order_id', 'in', $order_ids)->field('id,goods_id,name,num,goods_spec_one_id,goods_spec_two_id,goods_spec_name')->select();
        foreach ($arr as $key => $value) {
            $stock_num = DB::name('goods_stock')
                ->where(['goods_id' => $value['goods_id'], 'goods_spec_one_id' => $value['goods_spec_one_id'], 'goods_spec_two_id' => $value['goods_spec_two_id']])
                ->value('num');
            if ($value['num'] > $stock_num) {
                //$this->error($value['name'] . $value['goods_spec_name'] . '库存不足', '', 201);
            }
        }
    }

    //支付获取金额
    public function getPrice($paycode)
    {
        $type = substr($paycode, 8, 1);
        //判断是支付单号,还是订单号
        $where = [];
        if ($type == 1) {//支付单号=1,合并支付
            // 查询该订单下所有商品库存信息
            $where['paycode'] = $paycode;
        } elseif ($type == 2) { //2= 拆单支付
            $where['ordernum'] = $paycode;
        }
        $order_ids = DB::name('order')->where($where)->field('allprice')->select();
        $price = 0;
        foreach ($order_ids as $key => $value) {
            $price = $price + $value['allprice'];
        }
        return $price;
    }

    // 支付之后减库存 +加销量
    public function dec_kucun($paycode)
    {
        $type = substr($paycode, 8, 1);
        //判断是支付单号,还是订单号
        $where = [];
        if ($type == 1) {//支付单号=1,合并支付  
            // 查询该订单下所有商品库存信息
            $where['paycode'] = $paycode;
        } elseif ($type == 2) { //2= 拆单支付
            $where['ordernum'] = $paycode;
        }
        $order_ids = DB::name('order')->where($where)->column('id');
        $arr = DB::name('orderdetail')->where('order_id', 'in', $order_ids)->field('id,goods_id,name,num,goods_spec_one_id,goods_spec_two_id,goods_spec_name')->select();
        foreach ($arr as $key => $value) {
            $stock_num = DB::name('goods_stock')
                ->where(['goods_id' => $value['goods_id'], 'goods_spec_one_id' => $value['goods_spec_one_id'], 'goods_spec_two_id' => $value['goods_spec_two_id']])
                ->setDec('num', $value['num']);
            DB::name('goods')->where('id', $value['goods_id'])->setInc('sale_num', $value['num']);  //增加销量
        }
    }

    //余额支付
//    public function yue_zhifu()
//    {
//        $request = Request::instance();
//        $paycode = $request->param("paycode") ?: '';//订单号
//        $allprice = $request->param("price") ?: 0;//实付金额
//        // $uid = $request->param("uid")?:0;//用户id
//
//        if (!$paycode) {
//            $this->error('订单号不能为空', '', 201);
//        }
//        if ($allprice != 0) {
//            $this->error('实付金额不为0,无法进行余额支付', '', 201);
//        }
//        //检查库存是否充足
//        $this->pd_kucun($paycode);
//        // $vouchers = DB::name('userhome')->where('id',$uid)->value('vouchers');
//        // if ($dikou > $vouchers) {
//        //     $this->error('立减券余额不足','',201);
//        // }
//
//        $type = substr($paycode, 8, 1);
//        //判断是支付单号,还是订单号
//        if ($type == 1) {//支付单号=1,合并支付
//            //更改订单状态
//            // $order = Db::name("order")->where('paycode',$paycode)->find();
//            DB::name('order')->where('paycode', $paycode)->update(['paytime' => time(), 'paytype' => 3, 'status' => 2, 'orderpaytype' => 1]);
//            // $o_arr = Db::name("order")->where('paycode',$paycode)->select();
//        } elseif ($type == 2) { //2= 拆单支付
//            # code...
//            //更改订单状态
//            // $order = Db::name("order")->where('ordernum',$paycode)->find();
//            DB::name('order')->where('ordernum', $paycode)->update(['paytime' => time(), 'paytype' => 3, 'status' => 2, 'orderpaytype' => 2]);
//            // $o_arr = Db::name("order")->where('ordernum',$paycode)->select();
//        }
//        //支付完成减库存
//        $this->dec_kucun($paycode);
//        $this->success('ok', '', 200);
//    }

    //支付宝支付
    public function zhifubao()
    {
        //支付宝
        include "./aop/AopClient.php";
        include "./aop/AopCertClient.php";
        include "./aop/request/AlipayTradeAppPayRequest.php";
        $c = new \AopCertClient;
        $root_path = getSystem("root_path");
        $appCertPath = $root_path . "public/zhengshu/appCertPublicKey_2021002182617884.crt";//应用公钥
        $alipayCertPath = $root_path . "public/zhengshu/alipayCertPublicKey_RSA2.crt";//支付宝公钥
        $rootCertPath = $root_path . "public/zhengshu/alipayRootCert.crt";//支付宝根证书
        $c->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $c->appId = "2021002182617884";
        $c->rsaPrivateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCykKr+nuwgwviNEAEdUD7BomIPSFn25XM7a2dzaBLLwVZbC1AZ6PsCGjDyIeTi/L8WECZ/m251cc05ntBfIlnIawwX8DsnZB7/O8usL21rjVyatUFTzW+gz0v7/H0OAj/503g8jBczWFbnxONmstaAo7VCLQ163qfkEYB3a3uo/jMbm0TmvJ50QKh75uvazlptXBxmqUlEhj1qicpdyhz99cbS/2bn4Ci+5CcY9UIBIlXn/iGCWQ/CvxpXbtKGKUQu9UmdROCcM5D5SmEiSWTBn5Pt5tJzTWqK3h+wxlaArdAvf/YOJUin7GoXgjSguRJ28NXftsmt0vT9Johe+cAxAgMBAAECggEATHpjkjw0u+9ljt0s7QYiasKGpy8AwRsS2H8uxqHrcvMybjoRK5e6cfMPxZS4uHMx0FxIcNz8WTbNhAE+E5DdzVXzzwjn/P4HvJ86o1uIzMi1wdkhyqexSLmgPKOuV+KkzfZBiAUkJqyORCPylVjBQEVda6NqI5bbZ3YLhJo3U3Ab4uBwT8YG8SzETFGHbG8Vqvb4rkFuMUSWm2aczD2JVRYuPoTmjsSezp9x9s6f+wsIqZC/5PmEMG0xfH9fUEXs+OHBVVu58JCJMwo4EwewBN8fWQTGLPJIZiUsLqtWCUHJ7/wSNU/Mp8RtDzaXKFfiuw8Mrc4J2dldUOOlXqS6AQKBgQDu7LaupzOsD3VizUIsxRoG/iIIIktARJJgoRxo+HU0vJ31tQbMntgqR5/VMp4tXa5tCSUZYgYSL7C1bqfHXouHDGj4/OZ+2cGqpYnGGfgNmlgoVi5hb4ncG72ggOYkDwsgv8mCFlyTvDykTb1M5z+upm2uxrIdVK55RRf88V2RIQKBgQC/U6LPGksYUtRcZCQGEa18FWT3aHlRun5m9fEdCjdMGXkhbxPMiFDg/JFtaeVzo7CUxBgMpLPpTOO/gT6FtWPsJvusP67W03yQR7ysdZKtrGPBXARwmQPHahGsV+2BoXk2kObVuc1EaA0oZFOLaJp1sOKEkJIf1zPU1PgBfSZ9EQKBgQCr0buGWmPEhtFqHiZKv+v5v2SF6POo4idKKlKeAp93L3WBL5AWMt1Nenis/1vVUBuR+hOd72piRb2UnGE39PvuQLR06ppv+vVVXPp5Zk+GqMphJ6jvFSFVEvYJqOjYYaElCgdF8ALfk20g028hEOQxGyqhl+6bPTzDpTadBo69QQKBgQCSssQg2948djYR6U6dwKwuehECin6LJd2JgIYxaAXiOZ3g/tRFfTfWapHvPMUMF7RrPLfb6eVwut3dlnGj/+LvzSwndGTQnzPhRL/r0/J1a7rJJY7Z7tkw66lFZd3cCT1xk0ULFv3Gt6lvEQ3l1HyqRMhKMLd55n39cJYAPj9moQKBgBuuK0vSf+9BhqK8/msXlPAYEHv/LFFH1ufvYKu6uPZuGWYWJsrFc+l/xhr1tmebPnENhSb5cZHRdwnq09K0HAGKV1NvNmQdrnvFAOANdb22Ovu8Q4Bbp1NVp28IjaDOR6CAXOcCM1HUJVMuqHHQ3123ISp10W2JNE67ss49lnB0';
        $c->format = "json";
        $c->charset = "GBK";
        $c->signType = "RSA2";
        //调用getPublicKey从支付宝公钥证书中提取公钥
        $c->alipayrsaPublicKey = $c->getPublicKey($alipayCertPath);
        //是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
        $c->isCheckAlipayPublicCert = true;
        //调用getCertSN获取证书序列号
        $c->appCertSN = $c->getCertSN($appCertPath);
        //调用getRootCertSN获取支付宝根证书序列号
        $c->alipayRootCertSN = $c->getRootCertSN($rootCertPath);
        $request2 = new \AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数
        $request = Request::instance();
        $yue_sn = $request->param("paycode") ?: '';//订单号
        //$money = $request->param("price") ?: '100000';//支付金额

        if (!$yue_sn) {
            $this->error('单号不能为空', '', 201);
        }
        $money = $this->getPrice($yue_sn);
        //检查库存是否充足
        $this->pd_kucun($yue_sn);

        if ($money == 0) {
            $this->error('金额不能是0', '', 201);
        }
        $remark = '云仓线上支付';
        // $yue_sn = time();//这里是单号
        // $money = '0.01';
        $bizcontent = "{\"body\":\"云仓小店\","
            . "\"subject\": \"{$remark}\","
            . "\"out_trade_no\": \"{$yue_sn}\","
            . "\"timeout_express\": \"30m\","
            . "\"total_amount\": \"{$money}\","
            . "\"product_code\":\"QUICK_MSECURITY_PAY\""
            . "}";
        // $notify_url = "https://".$_SERVER['SERVER_NAME']."/api/index/zfb_callback";

        $notify_url = "https://" . $_SERVER['SERVER_NAME'] . "/api/order/zfb_callback";
        // echo $notify_url;die;

        $request2->setNotifyUrl($notify_url);
        $request2->setBizContent($bizcontent);
        $response = $c->sdkExecute($request2);
        $this->success('成功', $response, 200);
    }

//    public function zhifubao_pc()
//    {
//        //支付宝
//        include "./aop/AopClient.php";
//        include "./aop/AopCertClient.php";
//        include "./aop/request/AlipayTradePagePayRequest.php";
//        $c = new \AopCertClient;
//        $root_path = getSystem("root_path");
//        $appCertPath = $root_path . "public/zhengshu/appCertPublicKey_2021002182617884.crt";//应用公钥
//        $alipayCertPath = $root_path . "public/zhengshu/alipayCertPublicKey_RSA2.crt";//支付宝公钥
//        $rootCertPath = $root_path . "public/zhengshu/alipayRootCert.crt";//支付宝根证书
//        $c->gatewayUrl = "https://openapi.alipay.com/gateway.do";
//        $c->appId = "2021002182617884";
//        $c->rsaPrivateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCykKr+nuwgwviNEAEdUD7BomIPSFn25XM7a2dzaBLLwVZbC1AZ6PsCGjDyIeTi/L8WECZ/m251cc05ntBfIlnIawwX8DsnZB7/O8usL21rjVyatUFTzW+gz0v7/H0OAj/503g8jBczWFbnxONmstaAo7VCLQ163qfkEYB3a3uo/jMbm0TmvJ50QKh75uvazlptXBxmqUlEhj1qicpdyhz99cbS/2bn4Ci+5CcY9UIBIlXn/iGCWQ/CvxpXbtKGKUQu9UmdROCcM5D5SmEiSWTBn5Pt5tJzTWqK3h+wxlaArdAvf/YOJUin7GoXgjSguRJ28NXftsmt0vT9Johe+cAxAgMBAAECggEATHpjkjw0u+9ljt0s7QYiasKGpy8AwRsS2H8uxqHrcvMybjoRK5e6cfMPxZS4uHMx0FxIcNz8WTbNhAE+E5DdzVXzzwjn/P4HvJ86o1uIzMi1wdkhyqexSLmgPKOuV+KkzfZBiAUkJqyORCPylVjBQEVda6NqI5bbZ3YLhJo3U3Ab4uBwT8YG8SzETFGHbG8Vqvb4rkFuMUSWm2aczD2JVRYuPoTmjsSezp9x9s6f+wsIqZC/5PmEMG0xfH9fUEXs+OHBVVu58JCJMwo4EwewBN8fWQTGLPJIZiUsLqtWCUHJ7/wSNU/Mp8RtDzaXKFfiuw8Mrc4J2dldUOOlXqS6AQKBgQDu7LaupzOsD3VizUIsxRoG/iIIIktARJJgoRxo+HU0vJ31tQbMntgqR5/VMp4tXa5tCSUZYgYSL7C1bqfHXouHDGj4/OZ+2cGqpYnGGfgNmlgoVi5hb4ncG72ggOYkDwsgv8mCFlyTvDykTb1M5z+upm2uxrIdVK55RRf88V2RIQKBgQC/U6LPGksYUtRcZCQGEa18FWT3aHlRun5m9fEdCjdMGXkhbxPMiFDg/JFtaeVzo7CUxBgMpLPpTOO/gT6FtWPsJvusP67W03yQR7ysdZKtrGPBXARwmQPHahGsV+2BoXk2kObVuc1EaA0oZFOLaJp1sOKEkJIf1zPU1PgBfSZ9EQKBgQCr0buGWmPEhtFqHiZKv+v5v2SF6POo4idKKlKeAp93L3WBL5AWMt1Nenis/1vVUBuR+hOd72piRb2UnGE39PvuQLR06ppv+vVVXPp5Zk+GqMphJ6jvFSFVEvYJqOjYYaElCgdF8ALfk20g028hEOQxGyqhl+6bPTzDpTadBo69QQKBgQCSssQg2948djYR6U6dwKwuehECin6LJd2JgIYxaAXiOZ3g/tRFfTfWapHvPMUMF7RrPLfb6eVwut3dlnGj/+LvzSwndGTQnzPhRL/r0/J1a7rJJY7Z7tkw66lFZd3cCT1xk0ULFv3Gt6lvEQ3l1HyqRMhKMLd55n39cJYAPj9moQKBgBuuK0vSf+9BhqK8/msXlPAYEHv/LFFH1ufvYKu6uPZuGWYWJsrFc+l/xhr1tmebPnENhSb5cZHRdwnq09K0HAGKV1NvNmQdrnvFAOANdb22Ovu8Q4Bbp1NVp28IjaDOR6CAXOcCM1HUJVMuqHHQ3123ISp10W2JNE67ss49lnB0';
//        $c->format = "json";
//        $c->charset = "GBK";
//        $c->signType = "RSA2";
//        //调用getPublicKey从支付宝公钥证书中提取公钥
//        $c->alipayrsaPublicKey = $c->getPublicKey($alipayCertPath);
//        //是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
//        $c->isCheckAlipayPublicCert = true;
//        //调用getCertSN获取证书序列号
//        $c->appCertSN = $c->getCertSN($appCertPath);
//        //调用getRootCertSN获取支付宝根证书序列号
//        $c->alipayRootCertSN = $c->getRootCertSN($rootCertPath);
//        $request2 = new \AlipayTradePagePayRequest();
//        //SDK已经封装掉了公共参数，这里只需要传入业务参数
//        $request = Request::instance();
//        $yue_sn = $request->param("paycode") ?: '';//订单号
//        //$money = $request->param("price") ?: '100000';//支付金额
//
//        if (!$yue_sn) {
//            $this->error('单号不能为空', '', 201);
//        }
//        $money = $this->getPrice($yue_sn);
//        //检查库存是否充足
//        $this->pd_kucun($yue_sn);
//
//        if ($money == 0) {
//            $this->error('金额不能是0', '', 201);
//        }
//        $remark = '云仓线上支付';
//        // $yue_sn = time();//这里是单号
//        // $money = '0.01';
//        $bizcontent = [
//            "out_trade_no"=>$yue_sn,
//            "total_amount"=>$money,
//            "subject"=>$remark,
//            "product_code"=>"FAST_INSTANT_TRADE_PAY",
//            "qr_pay_mode"=>2,
//            "timeout_express"=>"30m"
//        ];
//        $bizcontent = json_encode($bizcontent);
//        // $notify_url = "https://".$_SERVER['SERVER_NAME']."/api/index/zfb_callback";
//
//        $notify_url = "https://" . $_SERVER['SERVER_NAME'] . "/api/order/zfb_callback";
//        // echo $notify_url;die;
//
//        $request2->setNotifyUrl($notify_url);
//        $request2->setBizContent($bizcontent);
//        $response = $c->sdkExecute($request2);
//        $this->success('成功', $response, 200);
//    }

    public function zhifubao_pc()
    {

        $request = Request::instance();
        $yue_sn = $request->param("paycode") ?: '';//订单号
        //$money = $request->param("price") ?: '100000';//支付金额
        if (!$yue_sn) {
            $this->error('单号不能为空', '', 201);
        }
        $money = $this->getPrice($yue_sn);
        if ($money == 0) {
            $this->error('金额不能是0', '', 201);
        }
        //检查库存是否充足
        $this->pd_kucun($yue_sn);
        $remark = '云仓线上支付';
        //支付宝
        include "./aop/AopClient.php";
        include "./aop/AopCertClient.php";
        include "./aop/request/AlipayTradePagePayRequest.php";
        $notify_url = "https://" . $_SERVER['SERVER_NAME'] . "/api/order/zfb_callback";
        $root_path = getSystem("root_path");
        $appCertPath = $root_path . "public/zhengshu/appCertPublicKey_2021002182617884.crt";//应用公钥
        $alipayCertPath = $root_path . "public/zhengshu/alipayCertPublicKey_RSA2.crt";//支付宝公钥
        $rootCertPath = $root_path . "public/zhengshu/alipayRootCert.crt";//支付宝根证书
        $aop = new \AopCertClient;
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2021002182617884';
        $aop->rsaPrivateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCykKr+nuwgwviNEAEdUD7BomIPSFn25XM7a2dzaBLLwVZbC1AZ6PsCGjDyIeTi/L8WECZ/m251cc05ntBfIlnIawwX8DsnZB7/O8usL21rjVyatUFTzW+gz0v7/H0OAj/503g8jBczWFbnxONmstaAo7VCLQ163qfkEYB3a3uo/jMbm0TmvJ50QKh75uvazlptXBxmqUlEhj1qicpdyhz99cbS/2bn4Ci+5CcY9UIBIlXn/iGCWQ/CvxpXbtKGKUQu9UmdROCcM5D5SmEiSWTBn5Pt5tJzTWqK3h+wxlaArdAvf/YOJUin7GoXgjSguRJ28NXftsmt0vT9Johe+cAxAgMBAAECggEATHpjkjw0u+9ljt0s7QYiasKGpy8AwRsS2H8uxqHrcvMybjoRK5e6cfMPxZS4uHMx0FxIcNz8WTbNhAE+E5DdzVXzzwjn/P4HvJ86o1uIzMi1wdkhyqexSLmgPKOuV+KkzfZBiAUkJqyORCPylVjBQEVda6NqI5bbZ3YLhJo3U3Ab4uBwT8YG8SzETFGHbG8Vqvb4rkFuMUSWm2aczD2JVRYuPoTmjsSezp9x9s6f+wsIqZC/5PmEMG0xfH9fUEXs+OHBVVu58JCJMwo4EwewBN8fWQTGLPJIZiUsLqtWCUHJ7/wSNU/Mp8RtDzaXKFfiuw8Mrc4J2dldUOOlXqS6AQKBgQDu7LaupzOsD3VizUIsxRoG/iIIIktARJJgoRxo+HU0vJ31tQbMntgqR5/VMp4tXa5tCSUZYgYSL7C1bqfHXouHDGj4/OZ+2cGqpYnGGfgNmlgoVi5hb4ncG72ggOYkDwsgv8mCFlyTvDykTb1M5z+upm2uxrIdVK55RRf88V2RIQKBgQC/U6LPGksYUtRcZCQGEa18FWT3aHlRun5m9fEdCjdMGXkhbxPMiFDg/JFtaeVzo7CUxBgMpLPpTOO/gT6FtWPsJvusP67W03yQR7ysdZKtrGPBXARwmQPHahGsV+2BoXk2kObVuc1EaA0oZFOLaJp1sOKEkJIf1zPU1PgBfSZ9EQKBgQCr0buGWmPEhtFqHiZKv+v5v2SF6POo4idKKlKeAp93L3WBL5AWMt1Nenis/1vVUBuR+hOd72piRb2UnGE39PvuQLR06ppv+vVVXPp5Zk+GqMphJ6jvFSFVEvYJqOjYYaElCgdF8ALfk20g028hEOQxGyqhl+6bPTzDpTadBo69QQKBgQCSssQg2948djYR6U6dwKwuehECin6LJd2JgIYxaAXiOZ3g/tRFfTfWapHvPMUMF7RrPLfb6eVwut3dlnGj/+LvzSwndGTQnzPhRL/r0/J1a7rJJY7Z7tkw66lFZd3cCT1xk0ULFv3Gt6lvEQ3l1HyqRMhKMLd55n39cJYAPj9moQKBgBuuK0vSf+9BhqK8/msXlPAYEHv/LFFH1ufvYKu6uPZuGWYWJsrFc+l/xhr1tmebPnENhSb5cZHRdwnq09K0HAGKV1NvNmQdrnvFAOANdb22Ovu8Q4Bbp1NVp28IjaDOR6CAXOcCM1HUJVMuqHHQ3123ISp10W2JNE67ss49lnB0';
        //$aop->alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAspCq/p7sIML4jRABHVA+waJiD0hZ9uVzO2tnc2gSy8FWWwtQGej7Ahow8iHk4vy/FhAmf5tudXHNOZ7QXyJZyGsMF/A7J2Qe/zvLrC9ta41cmrVBU81voM9L+/x9DgI/+dN4PIwXM1hW58TjZrLWgKO1Qi0Net6n5BGAd2t7qP4zG5tE5ryedECoe+br2s5abVwcZqlJRIY9aonKXcoc/fXG0v9m5+AovuQnGPVCASJV5/4hglkPwr8aV27ShilELvVJnUTgnDOQ+UphIklkwZ+T7ebSc01qit4fsMZWgK3QL3/2DiVIp+xqF4I0oLkSdvDV37bJrdL0/SaIXvnAMQIDAQAB';
        //调用getPublicKey从支付宝公钥证书中提取公钥
        $aop->alipayrsaPublicKey = $aop->getPublicKey($alipayCertPath);
        //是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
        $aop->isCheckAlipayPublicCert = true;
        //调用getCertSN获取证书序列号
        $aop->appCertSN = $aop->getCertSN($appCertPath);
        //调用getRootCertSN获取支付宝根证书序列号
        $aop->alipayRootCertSN = $aop->getRootCertSN($rootCertPath);
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'UTF-8';
        $aop->format = 'json';
        $object = new \stdClass();
        $object->out_trade_no = $yue_sn;
        $object->total_amount = $money;
        $object->subject = $remark;
        $object->product_code = 'FAST_INSTANT_TRADE_PAY';
        $object->time_expire = date("Y-m-d H:i:s", strtotime("+30 minute"));
        //return var_dump($object->time_expire);
        //$object->qr_pay_mode = '2';
        $json = json_encode($object);
        $request = new \AlipayTradePagePayRequest();
        $request->setNotifyUrl($notify_url);
        $request->setBizContent($json);
        $result = $aop->pageExecute($request, "get");
        $this->success('成功', $result, 200);
    }


    //支付宝回调
    public function zfb_callback()
    {
        //下面三个文件路径一定要改正确   
        //支付宝
        include "./aop/AopClient.php";
        include "./aop/AopCertClient.php";
        include "./aop/request/AlipayTradeAppPayRequest.php";
        $root_path = getSystem("root_path");
        $alipayCertPath = $root_path . "public/zhengshu/alipayCertPublicKey_RSA2.crt";//支付宝公钥
        $aop = new \AopClient();
        $c = new \AopCertClient();
        $aop->alipayrsaPublicKey = $c->getPublicKey($alipayCertPath);
        file_put_contents('./success_zfb_cz.txt', var_export($_POST, TRUE));
        $flag = $aop->rsaCheckV1($_POST, NULL, "RSA2");

        DB::name('log')->insert(['content' => json_encode($_POST), 'type' => "ZFB"]);

        if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
            // file_put_contents('./asdf.txt', '123');
            $type = substr($_POST['out_trade_no'], 8, 1);
            //判断是支付单号,还是订单号
            if ($type == 1) {//支付单号=1,合并支付  
                //更改订单状态
                $order = Db::name("order")->where('paycode', $_POST['out_trade_no'])->find();
                DB::name('order')->where('paycode', $_POST['out_trade_no'])->update(['paytime' => time(), 'paytype' => 2, 'status' => 2, 'orderpaytype' => 1]);
                // $o_arr = Db::name("order")->where('paycode',$_POST['out_trade_no'])->select();                 
            } elseif ($type == 2) { //2= 拆单支付
                # code...
                //更改订单状态
                $order = Db::name("order")->where('ordernum', $_POST['out_trade_no'])->find();
                DB::name('order')->where('ordernum', $_POST['out_trade_no'])->update(['paytime' => time(), 'paytype' => 2, 'status' => 2, 'orderpaytype' => 2]);
                // $o_arr = Db::name("order")->where('ordernum',$_POST['out_trade_no'])->select();
            }
            if (isset($order)) {
                $this->distribution($order);
            }
            //支付完成减库存
            $this->dec_kucun($_POST['out_trade_no']);

            echo 'success';

        } else {
            file_put_contents('./3333.txt', "3333");
            echo 'fail';
        }
    }

    // 微信app支付
    public function weixin_pay()
    {
        $request = Request::instance();

        $payorder_num = $request->param("paycode") ?: '';//订单号
        //$total_fee = $request->param("price") ?: '100000';//支付金额
        $this->setWxGet($payorder_num);
        $total_fee = $this->getPrice($payorder_num);
        //检查库存是否充足
        $this->pd_kucun($payorder_num);
        if ($total_fee == 0) {
            $this->error('金额不能是0', '', 201);
        }

        //...
        include './WeixinPay.php';
        $wx = new \WeixinPay();//实例化微信支付控制器
        $root_http = getSystem("root_http");
        $http = $root_http . $_SERVER['SERVER_NAME'];
        $body = "线上消费";
        $total_fee = $total_fee * 100;
        // $total_fee = 1;//支付金额(乘以100)
        $notify_url = $http . "/api/order/wx_callback_api";
        $order = $wx->getPrePayOrder($body, $payorder_num, $total_fee, $notify_url);
        //dump($order);die;
        if (isset($order['prepay_id'])) {//判断返回参数中是否有prepay_id
            $order1 = $wx->getOrder($order['prepay_id']);//执行二次签名返回参数
            //dump($order1);die;
            $this->success('成功', $order1, 200);
        } else {
            $this->error('失败', $order['return_msg'], 201);
        }
    }

    // 微信pc支付
    public function weixin_pc_pay()
    {
        $request = Request::instance();

        $payorder_num = $request->param("paycode") ?: '';//订单号
        //$total_fee = $request->param("price") ?: '100000';//支付金额
        $this->setWxGet($payorder_num);
        $total_fee = $this->getPrice($payorder_num);
        //检查库存是否充足
        $this->pd_kucun($payorder_num);
        //return var_dump($total_fee);

        if ($total_fee == 0) {
            $this->error('金额不能是0', '', 201);
        }
        //...
        include './WeixinPay.php';
        $wx = new \WeixinPay();//实例化微信支付控制器
        $root_http = getSystem("root_http");
        $http = $root_http . $_SERVER['SERVER_NAME'];
        $body = "线上消费";
        $total_fee = $total_fee * 100;
        // $total_fee = 1;//支付金额(乘以100)
        $notify_url = $http . "/api/order/wx_callback_api";
        $order = $wx->getPrePcPayOrder($body, $payorder_num, $total_fee, $notify_url);
        //dump($order);die;
        if (isset($order['code_url'])) {//判断返回参数中是否有prepay_id
            //$order1 = $wx->getOrder($order['prepay_id']);//执行二次签名返回参数
            //dump($order1);die;
            $this->success('成功', $order['code_url'], 200);
        } else {
            $this->error('失败', $order['return_msg'], 201);
        }
    }

    //微信小程序支付
    public function wx_xcx_pay()
    {
        $request = Request::instance();
        $userhome_id = $request->param("userhome_id") ?: '';//用户id
        $payorder_num = $request->param("paycode") ?: '';//订单号
        //$total_fee = $request->param("price") ?: '100000';//支付金额
        $openid = $request->param("openid");//支付金额
        $this->setWxGet($payorder_num);
        $total_fee = $this->getPrice($payorder_num);
        if ($total_fee == 0) {
            $this->error('金额不能是0', '', 201);
        }
        //检查库存是否充足
        $this->pd_kucun($payorder_num);
        // dump($userhome_id);
        // dump($payorder_num);
        // dump($total_fee);die;
        require_once "./WeixinPayXcx.php";
        $body = "云仓小店订单支付";
        $total_fee = $total_fee * 100;
        // $total_fee = 1;
        $root_http = getSystem("root_http");
        $http = $root_http . $_SERVER['SERVER_NAME'];
        $notify_url = $http . "/api/order/wx_callback_api";
        //return var_dump($notify_url);
        if (!isset($openid) || empty($openid)) {
            $xcxopenid = DB::name('userhome')->where('id', $userhome_id)->value('appletOpenid');
            if (empty($xcxopenid)) {
                $xcxopenid = DB::name('userhome')->where('id', $userhome_id)->value('xcxopenid');
            }
        } else {
            $xcxopenid = $openid;
        }
        // $xcxopenid = 'oj6aC5ZRZ1B4Gaej0DbGI0cG5640';
        $weixinpay = new \WeixinPayXcx('wx4a40935421da4a92', $xcxopenid, '1615039358', '7f63d80284392beae6974f43c5c40a59', $payorder_num, $body, $total_fee, $notify_url);
        $return = $weixinpay->pay();
        $this->success('ok', $return, 200);
    }

    public function setWxGet($paycode)
    {
        $num = DB::name('order_get_wx')->where(['paycode' => $paycode])->count();
        if (!$num) {
            DB::name('order_get_wx')->insert(['paycode' => $paycode, 'createTime' => date("Y-m-d H:i:s")]);
        }
    }

    //支付回调
    public function wx_callback_api()
    {
        $xml = file_get_contents("php://input");
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        DB::name('log')->insert(['content' => "213123", 'type' => "WX"]);
        ksort($data);
        $buff = '';
        foreach ($data as $k => $v) {
            if ($k != 'sign') {
                $buff .= $k . '=' . $v . '&';
            }
        }
        $stringSignTemp = $buff . 'key=7f63d80284392beae6974f43c5c40a59';//key为证书密钥
        $sign = strtoupper(md5($stringSignTemp));
        //判断算出的签名和通知信息的签名是否一致
        if ($sign == $data['sign']) {
            if ($data['result_code'] == "SUCCESS") {
                if ($data['return_code'] == "SUCCESS") {
                    // $type = substr($data['out_trade_no'], 8,1);
                    //业务处理
                    $out_trade_no = $data['out_trade_no'];
                    $order_get_wx = DB::name('order_get_wx')->where(['paycode' => $out_trade_no])->find();
                    if ($order_get_wx) {
                        $this->updateOrderStatusWx($out_trade_no, "GO");
                    }
                }
                //处理完成之后，告诉微信成功结果
                echo exit('<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>');
            }
        } else {
            echo exit('<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[FAIL]]></return_msg></xml>');
        }
    }

    public function queryOrderWx()
    {
        require_once "./WeixinPayXcx.php";
        $startTime = date("Y-m-d H:i:s", strtotime("-0 minute"));
        $endTime = date("Y-m-d H:i:s", strtotime("-35 minute"));
        $order_get_wx_list = DB::name('order_get_wx')->where('createTime', "<=", $startTime)->where('createTime', ">=", $endTime)->order('createTime', 'asc')->select();
        //return var_dump($order_get_wx_list);
        $weixinpay = new \WeixinPayXcx('wx4a40935421da4a92', "", '1615039358', '7f63d80284392beae6974f43c5c40a59', "", "", "", "");
        foreach ($order_get_wx_list as $value) {
            $data = $weixinpay->orderQuery($value['paycode']);
            if ($data['return_code'] == "SUCCESS") {
                if ($data['trade_state'] == "SUCCESS") {
                    $order_get_wx = DB::name('order_get_wx')->where(['paycode' => $value['paycode']])->find();
                    if ($order_get_wx) {
                        $this->updateOrderStatusWx($value['paycode'], "SELECT");
                    }
                } else {
                    if ($data['trade_state'] != "NOTPAY" && $data['trade_state'] != "USERPAYING") {
                        DB::name('order_get_wx')->where(['paycode' => $value['paycode']])->delete();
                        DB::name('order_get_wx_copy')->insert(['paycode' => $value['paycode'], 'createTime' => date("Y-m-d H:i:s"), 'status' => $data['trade_state']]);
                    }
                }
            }
        }
    }

    public function updateOrderStatusWx($out_trade_no, $source)
    {
        DB::name('order_get_wx')->where(['paycode' => $out_trade_no])->delete();
        DB::name('order_get_wx_copy')->insert(['paycode' => $out_trade_no, 'createTime' => date("Y-m-d H:i:s"), 'status' => "SUCCESS", 'source' => $source]);
        //更改订单状态
        $type = substr($out_trade_no, 8, 1);
        //判断是支付单号,还是订单号
        if ($type == 1) {//支付单号=1,合并支付
            //更改订单状态
            $order = Db::name("order")->where('paycode', $out_trade_no)->find();
            DB::name('order')->where('paycode', $out_trade_no)->update(['paytime' => time(), 'paytype' => 1, 'status' => 2, 'orderpaytype' => 1]);
            // $o_arr = Db::name("order")->where('paycode',$data['out_trade_no'])->select();
        } elseif ($type == 2) { //2= 拆单支付
            # code...
            //更改订单状态
            $order = Db::name("order")->where('ordernum', $out_trade_no)->find();
            DB::name('order')->where('ordernum', $out_trade_no)->update(['paytime' => time(), 'paytype' => 1, 'status' => 2, 'orderpaytype' => 2]);
            // $o_arr = Db::name("order")->where('ordernum',$data['out_trade_no'])->select();
        }
        if (isset($order)) {
            $this->distribution($order);
        }
        //支付完成减库存
        $this->dec_kucun($out_trade_no);
    }

    public function orderDistribution()
    {
        $order = Db::name("order")->where('id', 750)->find();
        return var_dump($order);
        $this->distribution($order);
    }

    private function distribution($order)
    {
        if ($order['activityStatus'] == 0 || $order['activityStatus'] == 10) {
            DB::name('userhome')->where('id', $order['userhome_id'])->setInc('spend', $order['allprice']);//增加实际消费金额
            $orderDetail = DB::name('orderdetail')
                ->where('order_id', $order['id'])
                ->select();
            $user = Db::name("userhome")->where('id', $order['userhome_id'])->find();
            if (isset($orderDetail[0])) {
                $integral = 0;
                $shareUser = null;
                foreach ($orderDetail as $value) {
                    $integral += $value['integral'] * $value['num'];
                }
                if ($integral != 0) {
                    $system = Db::name("system")->where('systemId', 1)->find();
                    if ($system) {
                        $shareRate = $system['shareRate'];
                        $bigNum = $system['bigNum'];
                    } else {
                        $shareRate = 150;
                        $bigNum = 3;
                    }
                    //先给本人
                    $userScoreLog = [];
                    $userScoreLog['userId'] = $user['id'];
                    $userScoreLog['score'] = $integral;
                    $userScoreLog['source'] = "SHOP";
                    $userScoreLog['order_id'] = $order['id'];
                    $userScoreLog['createTime'] = date("Y-m-d H:i:s");
                    $userScoreLog['status'] = "WAIT";
                    $userScoreLog['ratio'] = 100;
                    //给分享人收益如果存在
                    $userScoreLogList = [];
                    $userScoreNum = 0;
                    $time = date("Y-m-d H:i:s");
//                if (isset($order['inviteUserPhone']) && !empty($order['inviteUserPhone'])) {
//                    $shareUser = DB::name('userhome t1')
//                        ->join('level t2', 't1.levelId=t2.levelId')
//                        ->whereIn('t1.id', $order['inviteUserId'])
//                        ->field('t1.id,t1.phone,t2.ratio,t2.weight,t2.levelId')
//                        ->find();
//                    if ($shareUser) {
//                        $userScoreLogList[0]['userId'] = $shareUser['id'];
//                        $userScoreLogList[0]['score'] = intval(($integral * 100) * $shareRate * $shareUser['weight']) / 1000000;
//                        $userScoreLogList[0]['source'] = "SHARE";
//                        $userScoreLogList[0]['order_id'] = $order['id'];
//                        $userScoreLogList[0]['createTime'] = $time;
//                        $userScoreLogList[0]['status'] = "WAIT";
//                        $userScoreLogList[0]['ratio'] = $shareRate;
//                        $userScoreLogList[0]['levelId'] = $shareUser['levelId'];
//                        $userScoreLogList[0]['break'] = "基数为$integral,比例为$shareRate,权重为" . $shareUser['weight'];
//                        $userScoreNum = 1;
//                    }
//                }
                    //查询收益链
                    $userRelation = Db::name("user_relation")->where('userId', $user['id'])->find();
                    if (isset($userRelation)) {
//                    //如果分享人不存在
//                    if (!isset($shareUser)) {
//                        //判断他的直推人
//                        $shareUser = DB::name('userhome t1')
//                            ->join('level t2', 't1.levelId=t2.levelId')
//                            ->whereIn('t1.id', $userRelation['inviteUserId'])
//                            ->field('t1.id,t1.phone,t2.ratio,t2.weight,t2.levelId')
//                            ->find();
//                        if ($shareUser) {
//                            $userScoreLogList[0]['userId'] = $shareUser['id'];
//                            $userScoreLogList[0]['score'] = intval(($integral * 100) * $shareRate * $shareUser['weight']) / 1000000;
//                            $userScoreLogList[0]['source'] = "SHARE";
//                            $userScoreLogList[0]['order_id'] = $order['id'];
//                            $userScoreLogList[0]['createTime'] = $time;
//                            $userScoreLogList[0]['status'] = "WAIT";
//                            $userScoreLogList[0]['ratio'] = $shareRate;
//                            $userScoreLogList[0]['levelId'] = $shareUser['levelId'];
//                            $userScoreLogList[0]['break'] = "基数为$integral,比例为$shareRate,权重为" . $shareUser['weight'];
//                            $userScoreNum = 1;
//                        }
//                    }
                        if (isset($userRelation['relationList']) && !empty($userRelation['relationList'])) {
                            //如果这个人存在收益链
                            $userSuperiorsIdList = explode(';', $userRelation['relationList']);
                            unset($userSuperiorsIdList[count($userSuperiorsIdList) - 1]);
                            unset($userSuperiorsIdList[0]);
                            $userSuperiorsIdList = array_values($userSuperiorsIdList);
                            $userSuperiorsList = DB::name('userhome t1')
                                ->join('level t2', 't1.levelId=t2.levelId')
                                ->whereIn('t1.id', $userSuperiorsIdList)
                                ->field('t1.id,t1.phone,t2.ratio,t2.internodeRatio,t2.levelId,t2.bigRatio')
                                ->select();
                            if (isset($userSuperiorsList[0])) {
                                $SVIPNum = 0;
                                foreach ($userSuperiorsIdList as $k => $v) {
                                    foreach ($userSuperiorsList as $key => $value) {
                                        if ($value['id'] == $v) {
                                            $ratio = 0;
                                            if ($k == 0) {
                                                $ratio = $value['ratio'];
                                            }
                                            if ($k == 1) {
                                                if ($value['levelId'] > 1) {
                                                    $ratio = $value['internodeRatio'];
                                                }
                                            }
                                            if ($value['levelId'] > 3) {
                                                $ratio = $value['ratio'];
                                                $SVIPNum++;
                                                if ($SVIPNum == $bigNum) {
                                                    $ratio = $value['bigRatio'];
                                                }
                                            }
                                            if ($ratio != 0) {
                                                $userScoreLogList[$key + $userScoreNum]['userId'] = $value['id'];
                                                $userScoreLogList[$key + $userScoreNum]['score'] = intval($integral * $ratio) / 100;
                                                $userScoreLogList[$key + $userScoreNum]['source'] = "SALE";
                                                $userScoreLogList[$key + $userScoreNum]['order_id'] = $order['id'];
                                                $userScoreLogList[$key + $userScoreNum]['createTime'] = $time;
                                                $userScoreLogList[$key + $userScoreNum]['status'] = "WAIT";
                                                $userScoreLogList[$key + $userScoreNum]['ratio'] = $ratio;
                                                $userScoreLogList[$key + $userScoreNum]['levelId'] = $value['levelId'];
                                                $userScoreLogList[$key + $userScoreNum]['break'] = "基数为$integral,比例为$ratio,权重为100";
                                            }
                                            break;
                                        }
                                    }
                                    if ($k == 1) {
                                        break;
                                    }
                                    if ($SVIPNum == $bigNum) {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    $userScoreLogList = array_values($userScoreLogList);
                    if (isset($userScoreLogList[0])) {
                        unset($key);
                        unset($value);
                        foreach ($orderDetail as $value) {
                            $integral = $value['integral'] * $value['num'];
                            $userScoreLog['score'] = $integral;
                            $userScoreLog['order_detail_id'] = $value['id'];
                            Db::name("user_income_score_log")->insert($userScoreLog);
//                        unset($k);
//                        unset($v);
//                        $insertUserScoreLogList = [];
//                        foreach ($userScoreLogList as $k => $v) {
//                            $insertUserScoreLogList[$k]['userId'] = $v['userId'];
//                            $insertUserScoreLogList[$k]['source'] = $v['source'];
//                            $insertUserScoreLogList[$k]['order_id'] = $v['order_id'];
//                            $insertUserScoreLogList[$k]['order_detail_id'] = $value['id'];
//                            $insertUserScoreLogList[$k]['createTime'] = $v['createTime'];
//                            $insertUserScoreLogList[$k]['ratio'] = $v['ratio'];
//                            $insertUserScoreLogList[$k]['break'] = $v['break'];
//                            $insertUserScoreLogList[$k]['levelId'] = $v['levelId'];
//                            $insertUserScoreLogList[$k]['status'] = $v['status'];
//                            if ($v['source'] == "SHARE") {
//                                $insertUserScoreLogList[$k]['score'] = intval(($integral * 100) * $shareRate * $shareUser['weight']) / 1000000;
//                            }
//                            if ($v['source'] == "SALE") {
//                                $insertUserScoreLogList[$k]['score'] = intval($integral * $v['ratio']) / 100;
//                            }
//                        }
//                        Db::name("user_income_score_log")->insertAll($insertUserScoreLogList);
                        }
                    } else {
                        unset($key);
                        unset($value);
                        foreach ($orderDetail as $value) {
                            $integral = $value['integral'] * $value['num'];
                            $userScoreLog['score'] = $integral;
                            $userScoreLog['order_detail_id'] = $value['id'];
                            Db::name("user_income_score_log")->insert($userScoreLog);
                        }
                    }
                }
                //添加团长收益
                $teamUser = DB::name('user_team t1')
                    ->join('user_collaborate t2', 't1.teamUserId=t2.userId')
                    ->join('userhome t3', 't2.userId=t3.id')
                    ->join('collaborate t4', 't2.collaborateId=t4.id')
                    ->where('t1.userId', $user['id'])
                    ->where('t2.status', 1)
                    ->where('t1.status', 1)
                    ->field('t3.id as uid,t3.phone,t4.rate,t4.id as collaborateId')
                    ->find();
                if ($teamUser) {
                    DB::name('orderdetail')
                        ->where('order_id', $order['id'])
                        ->update(['collaboratePhone' => $teamUser['phone']]);
                    unset($key);
                    unset($value);
                    $userTeamPriceLog = [];
                    $price = 0;
                    foreach ($orderDetail as $key => $value) {
                        //计算毛利
                        //$grossMargin = ((intval(strval($value['price'] * 100))) - (intval(strval($value['cost_price'] * 100))) - ((intval(strval($value['freightCostPrice'] * 100)) * $value['num'])) - ($value['price'] * $value['shuilv'])) / 100;
                        $grossMargin = intval((($value['integral'] * $value['num']) * 10000) / 0.3);
                        $userTeamPriceLog[$key]['userId'] = $teamUser['uid'];
                        $userTeamPriceLog[$key]['price'] = (($grossMargin * $teamUser['rate']) / 100) / 10000;
                        $userTeamPriceLog[$key]['source'] = "TEAM";
                        $userTeamPriceLog[$key]['createTime'] = date("Y-m-d H:i:s");
                        $userTeamPriceLog[$key]['ratio'] = $teamUser['rate'];
                        $userTeamPriceLog[$key]['collaborateId'] = $teamUser['collaborateId'];
                        $userTeamPriceLog[$key]['order_id'] = $order['id'];
                        $userTeamPriceLog[$key]['order_detail_id'] = $value['id'];
                        $userTeamPriceLog[$key]['break'] = "毛利增加一万倍为$grossMargin,比例为100,权重为" . $teamUser['rate'];
                        $price = $price + $userTeamPriceLog[$key]['price'];
                    }
                    DB::name('userhome')->where(['id' => $teamUser['uid']])->setInc("lockPrice", $price);
                    Db::name("user_team_price_log")->insertAll($userTeamPriceLog);
                }
            }
        }
    }

    //查询统计上个月代理商直接下级 B端小店 返现比例  每月1号统计上个月的数据
    //每月1日 1点钟01分 统计
    public function auto_store_in_daili()
    {
        set_time_limit(0);
        if (date("d H") != '01 01') {
            return '';
        }
        $bili = DB::name('bili')->where('id', 1)->find();
        //查询所有认证的 代理商
        $dailis = DB::name('userhome')->where('is_renzheng', 3)->field('id')->select();
        $user = DB::name('userhome');
        $store_fx_dailis = DB::name('store_fx_dailis');
        $dailishang_srdetails = DB::name('dailishang_srdetails');
        foreach ($dailis as $key => $value) {
            //查询个小店累计消费
            $num = 0;
            $leiji = $user->where('pid', $value['id'])->where('is_renzheng', 2)->field('id,spend')->select();
            foreach ($leiji as $k_1 => $v_1) {
                if ($v_1['spend'] > $bili['money']) {
                    //当前用户本月消费
                    $benyuexiaofei = $v_1['spend'] - $store_fx_dailis->where('userhome_id', $v_1['id'])->sum('money');
                    if ($benyuexiaofei > $bili['money']) {
                        $num += floor($benyuexiaofei / $bili['money']);
                        $yingkou_money = $num * $bili['money'];
                        //添加返现记录
                        $store_fx_dailis->insert(['userhome_id' => $v_1['id'], 'money' => $yingkou_money, 'time' => date('Y-m-d H:i:s')]);
                    }
                }
            }
            //判断是否符合条件2 或者返现条件3 
            $bl = 0;
            if ($num * $bili['money'] > $bili['condition3']) {
                $bl = $bili['proportion3'];
                // 判断是否满足条件3 
                $out = $num * $bili['money'] * ($bili['proportion3'] / 100);
            } elseif ($num * $bili['money'] > $bili['condition2']) {
                $bl = $bili['proportion2'];
                // 判断是否满足条件2
                $out = $num * $bili['money'] * ($bili['proportion2'] / 100);
            } else {
                $bl = $bili['proportion'];
                //都不满足 按照第一个比例进行给代理商分钱(返现)
                $out = $num * $bili['money'] * ($bili['proportion'] / 100);
            }
            //按照符合的比例给代理商增加返现数值
            $user->where('id', $value['id'])->setInc('money', $out);
            $dailis_arr = [];
            if ($num * $bili['money'] > 0) {
                // code...
                $dailis_arr['dls_uid'] = $value['id'];
                $dailis_arr['month_xs_money'] = $num * $bili['money'];//本月销售总金额
                $dailis_arr['month_bili'] = $bl;
                $dailis_arr['month_all_money'] = $out;
                $dailis_arr['month_yingfa_money'] = $out;
                $dailis_arr['month_yijiesuan'] = 0;
                $dailis_arr['createtime'] = time();
                $dailishang_srdetails->insert($dailis_arr);
            }

        }

    }
    //B端小店或者C端客户 获取下级的任意金额的消费返券10%
    //每小时统计
    public function auto_s_or_u_fanquan()
    {

        set_time_limit(0);
        $bili = DB::name('bili')->where('id', 2)->find();
        //查询所有小店店主或者c端用户
        $arr = DB::name('userhome')->where('is_renzheng', '<>', 3)->field('id')->select();
        $user = DB::name('userhome');
        $fanquan_log = DB::name('fanquan_log');
        $vouchers = DB::name('vouchers');
        foreach ($arr as $key => $value) {
            $user_and_dianzhu = $user->where('pid', $value['id'])->field('id,spend')->select();

            // dump($arr);die;
            foreach ($user_and_dianzhu as $k1 => $v1) {
                $user_money = $fanquan_log->where('userhome_id', $v1['id'])->sum('money');

                // dump($arr);die;
                // dump($v1['spend']*$bili['proportion']/100);die;
                if ($v1['spend'] > $user_money) {
                    $log = [];
                    $log['money'] = $v1['spend'] - $user_money;
                    $log['userhome_id'] = $v1['id'];
                    $log['time'] = date('Y-m-d H:i:s');
                    if ($log['money'] > 1) { //金额太小不做计算
                        // code...
                        $fanquan_log->insert($log);

                        $user->where('id', $value['id'])->setInc('vouchers', $log['money'] * $bili['proportion'] / 100);//下线给上线返券
                        //上线得到的返券记录
                        $vouchers->insert(['userhome_id' => $value['id'], 'bean_num' => $log['money'] * $bili['proportion'] / 100, 'type' => 5, 'user_id' => $v1['id'], 'createtime' => time()]);
                    }
                }
            }
        }
        $this->auto_dailis_down_fq();
        $this->auto_store_in_daili();

    }

    //代理商  获取下级的任意金额的消费返券5%
    //每小时统计
    public function auto_dailis_down_fq()
    {
        set_time_limit(0);
        $bili = DB::name('bili')->where('id', 3)->find();
        //查询所有代理商
        $arr = DB::name('userhome')->where('is_renzheng', 3)->field('id')->select();
        $user = DB::name('userhome');
        $fanquan_log = DB::name('fanquan_log_dailis');
        $vouchers = DB::name('vouchers');
        // dump($arr);die;
        foreach ($arr as $key => $value) {
            $user_and_dianzhu = $user->where('pid', $value['id'])->field('id,spend')->select();
            foreach ($user_and_dianzhu as $k2 => $v2) {
                //再查下第三级 
                $out_user = $user->where('pid', $v2['id'])->field('id,spend')->select();
                // if ($value['id']==34) {
                //     // code...
                //     dump($out_user);die;
                // }
                foreach ($out_user as $k3 => $v3) {
                    // code...
                    $user_money = $fanquan_log->where('userhome_id', $v3['id'])->sum('money');
                    if ($v3['spend'] > $user_money) {
                        $log = [];
                        $log['money'] = $v3['spend'] - $user_money;
                        $log['userhome_id'] = $v3['id'];
                        $log['time'] = date('Y-m-d H:i:s');
                        $fanquan_log->insert($log);
                        $user->where('id', $value['id'])->setInc('vouchers', $log['money'] * $bili['proportion'] / 100);
                        $vouchers_arr = [
                            'userhome_id' => $value['id'],
                            'bean_num' => $log['money'] * $bili['proportion'] / 100,
                            'type' => 5,
                            'user_id' => $v3['id'],
                            'createtime' => time(),
                        ];
                        $vouchers->insert($vouchers_arr);
                    }
                }
            }
        }
    }

    //支付后 添加供应商的订单同步
    public function gys_jiesuan_tongbu($arr = [])
    {
        $orderdetail = DB::name('orderdetail')->where('order_id', $arr['id'])->select();
        $gys_jiesuan = DB::name('gys_jiesuan');
        $goods = DB::name('goods');
        $goods_integral = DB::name('goods_integral');
        $jiesuan = [];
        foreach ($orderdetail as $key => $value) {
            if ($arr['is_integral'] == 1) {
                $goods_info = $goods_integral->where('id', $value['goods_id'])->field('shuilv,cost_price')->find();
            } else {
                $goods_info = $goods->where('id', $value['goods_id'])->field('shuilv,cost_price')->find();
            }
            $jiesuan[$key]['supplier_id'] = $arr['supplier_id'];
            $jiesuan[$key]['orderdetail_id'] = $value['id'];
            $jiesuan[$key]['goods_id'] = $value['goods_id'];
            $jiesuan[$key]['order_id'] = $value['order_id'];
            $jiesuan[$key]['dd_money'] = $value['num'] * $value['price'];
            // $jiesuan[$key]['cb_money'] = $value['num'] * $goods_info['cost_price'];
            $jiesuan[$key]['cb_money'] = $value['num'] * $this->get_cost_price($value['goods_id'], $value['goods_spec_one_id'], $value['goods_spec_two_id']);

            $jiesuan[$key]['yf_money'] = $arr['freight'];
            $jiesuan[$key]['se_money'] = $jiesuan[$key]['cb_money'] * $goods_info['shuilv'] / 100;
            $jiesuan[$key]['count_money'] = $jiesuan[$key]['cb_money'] + $arr['freight'] + $jiesuan[$key]['se_money'];
            $jiesuan[$key]['createtime'] = time();
            $arr['freight'] = 0;  //只有第一个子订单记录运费,剩余都按照0统计(运费不做拆分)

        }
        $gys_jiesuan->insertAll($jiesuan);
    }

    //添加供应商的订单同步
    public function auto_gys_ddtb()
    {
        $cronLog = [];
        $cronLog['url'] = "auto_gys_ddtb";
        $cronLog['createTime'] = date("Y-m-d H:i:s");
        DB::name('cron_log')->insert($cronLog);
        $order_info = DB::name('order')->where('paytime', '<>', '')->whereRaw('status != 6')->where('is_xs_sh_anniu', 1)->where('is_tbgysdd', 0)->select();
        // dump($order_info);die;
        if ($order_info) {
            foreach ($order_info as $key => $value) {
                $this->gys_jiesuan_tongbu($order_info[$key]);
                DB::name('order')->where('id', $value['id'])->update(['is_tbgysdd' => 1]);
            }
        }
    }

    public function aaaa()
    {
        $orderdetail = DB::name('orderdetail')->where('cost_price', 0)->select();
        dump($orderdetail);
        die;
        foreach ($orderdetail as $key => $value) {
            $cost = $this->get_cost_price($value['goods_id'], $value['goods_spec_one_id'], $value['goods_spec_two_id']);
            DB::name('orderdetail')->where('id', $value['id'])->update(['cost_price' => $cost, 'shuilv' => $this->get_shuilv($value['goods_id'])]);
        }
    }

    //计算确认收货7天后的订单 统计累计消费 和置为不显示售后按钮
    public function auto_7day_shouhuo()
    {
        $cronLog = [];
        $cronLog['url'] = "auto_7day_shouhuo";
        $cronLog['createTime'] = date("Y-m-d H:i:s");
        DB::name('cron_log')->insert($cronLog);
        $order_info = DB::name('order')->where('shouhuotime', '<', time() - 7 * 86400)->where('is_xs_sh_anniu', 1)->select();
        // dump($order_info);die;

        $order = DB::name('order');
        $orderdetail = DB::name('orderdetail');
        $user = DB::name('userhome');
        $user_sj_xiaofei = DB::name('user_sj_xiaofei');
        $tongji = DB::name('brand_tongji');
        $goods = DB::name('goods');
        $goods_integral = DB::name('goods_integral');
        $user = DB::name('userhome');
        $user = DB::name('userhome');
        $store_fq_tongji = DB::name('store_fq_tongji');
        if ($order_info) {
            // code...
            foreach ($order_info as $key => $value) {
                // $this->gys_jiesuan_tongbu($order_info[$key]);
                // echo 111;die;
                //按照商品返利模式给B端店主自己返券
                $is_renzheng = $user->where('id', $value['userhome_id'])->value('is_renzheng');
                if ($is_renzheng == 2 && $value['allprice'] > 0) { //是店主并且实际支付大于0元 才统计
                    $fanquan = $orderdetail->where('order_id', $value['id'])->where('is_count', 0)->field('id,userhome_id,return_mode_id,num,price')->select();
                    // dump($fanquan);die;
                    foreach ($fanquan as $k3 => $v3) {
                        $iscz = $store_fq_tongji->where('return_mode_id', $v3['return_mode_id'])->where('userhome_id', $v3['userhome_id'])->find();
                        $fanquan[$k3]['allprice'] = $v3['num'] * $v3['price'];
                        // dump($fanquan[$k3]);die;
                        if (!$iscz) {
                            unset($fanquan[$k3]['num']);
                            unset($fanquan[$k3]['price']);
                            $store_fq_tongji->insert($fanquan[$k3]);
                        } else {
                            $store_fq_tongji->where('return_mode_id', $v3['return_mode_id'])->where('userhome_id', $v3['userhome_id'])->setInc('allprice', $fanquan[$k3]['allprice']);
                        }
                        // dump($fanquan[$k3]);die;
                        $orderdetail->where('id', $v3['id'])->update(['is_count' => 1]);
                    }

                }
                $tongji_arr = [];
                $order->where('id', $value['id'])->update(['is_xs_sh_anniu' => 2]);//售后按钮不在显示
                if ($value['allprice'] > 0) {
                    $sjtkprice = $orderdetail->where('order_id', $value['id'])->sum('sjtkprice');
                    $out = $value['allprice'] - $sjtkprice - $value['freight'];//实付款-售后退的款-运费 = 实际消费金额
                    $user_sj_xiaofei->insert(['userhome_id' => $value['userhome_id'], 'money' => $out, 'time' => date('Y-m-d H:i:s')]);//添加实际消费统计

                }
                $tong = $orderdetail->where('order_id', $value['id'])->field('id as orderdetail_id,order_id,goods_id,')->select();
                foreach ($tong as $k1 => $v1) {
                    if ($value['is_integral'] == 1) {
                        $tong[$k1]['is_integral'] = 1;
                        $tong[$k1]['brand_id'] = $goods_integral->where('id', $v1['goods_id'])->value('brand_id');
                    } else {
                        $tong[$k1]['brand_id'] = $goods->where('id', $v1['goods_id'])->value('brand_id');
                    }
                    $tong[$k1]['createtime'] = time();
                }
                $tongji->insertAll($tong);   //添加品牌销量统计
            }
        }
        //$this->auto_tongji_store_fq();
    }

    //统计小店店主的商品购物返券
    public function auto_tongji_store_fq()
    {
        $return_mode = DB::name('return_mode')->select();
        $store_fq_tongji = DB::name('store_fq_tongji');
        $user = DB::name('userhome');
        $vouchers = DB::name('vouchers');
        foreach ($return_mode as $key => $value) {
            $arr = $store_fq_tongji->where('return_mode_id', $value['id'])->select();
            // dump($arr);die; 
            foreach ($arr as $k1 => $v1) {
                if ($v1['allprice'] - $v1['yfprice'] >= $value['money']) {
                    if ($v1['cishu'] >= $value['times']) {
                        $bili = ($value['proportion'] + $value['add_proportion'] * $value['times']) / 100;
                    } else {
                        $bili = ($value['proportion'] + $v1['cishu'] * $value['add_proportion']) / 100;
                    }
                    $store_fq_tongji->where('id', $v1['id'])->setInc('cishu');
                    $beishu = floor(($v1['allprice'] - $v1['yfprice']) / $value['money']);
                    $money = $beishu * $value['money'];
                    $store_fq_tongji->where('id', $v1['id'])->setInc('yfprice', $money);
                    $user->where('id', $v1['userhome_id'])->setInc('vouchers', $money * $bili);
                    $user->where('id', $v1['userhome_id'])->update(['end_rz_time' => time()]);
                    $vouchers->insert(['userhome_id' => $v1['userhome_id'], 'bean_num' => $money * $bili, 'type' => 10, 'createtime' => time()]);
                }
            }
        }
    }


}
